是否可以借助注释在我自己的代码之外编写代码?

时间:2015-01-21 14:43:05

标签: java aspectj load-time-weaving

我有一个想法,想知道,如果有可能,如果是,如何。 我正在为其他用户工作,以简化他们的生活。

我有两个注释。

达尔文:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Darwin {}

DarwinVersion:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DarwinVersion {}

一方面。

DarwinAspect:

public privileged aspect DarwinAspect {

private final static Logger LOGGER = LoggerFactory.getLogger(DarwinAspect.class);

after(): execution((@bla.Darwin *).new(..)) {
    int numberOfDarwinVersionFields = 0;
    LOGGER.debug("Try to add version!");
    try {
        Field darwinVersionField = null;
        for (Field field : thisJoinPoint.getTarget().getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(DarwinVersion.class)) {
                numberOfDarwinVersionFields++;
                LOGGER.debug("DarwinVersion found on field " + field + "!");
                darwinVersionField = field;
            }
        }
        if (numberOfDarwinVersionFields > 1) {
            LOGGER.error("To many @DarwinVersion annotations in class " + thisJoinPoint.getTarget().getClass() + "!");
        } else if (numberOfDarwinVersionFields == 0) {
            LOGGER.error("No DarwinVersion field found in class " + thisJoinPoint.getTarget().getClass() + "!");
        } else if (darwinVersionField != null) {
            LOGGER.debug("Set DarwinVersion on field " + darwinVersionField + "!");
            darwinVersionField.setAccessible(true);
            darwinVersionField.set(thisJoinPoint.getTarget(), VersionProvider.getVersion(thisJoinPoint.getTarget().getClass()));
        }
    } catch (IllegalAccessException e) {
        LOGGER.error(e.getLocalizedMessage());
    }
 }

}

(此代码将在调用构造函数后自动为每个对象设置DarwinVersion。)

我们的想法是编写任何类用户,他们使用注释声明他们的类。他们只应该将我的库添加到他们的类路径中。就像在这个例子中一样:

@Darwin
public class Example {

 @DarwinVersion
 private Long version;

 public static void main(String[] args) {

  Example example = new Example();
  System.out.println(example);

 }

 @Override
 public String toString() {
  return "Example{" + "version=" + version + '}';
 }
}

此代码正常运行,但仅限于我自己的项目。在包含Darwin-library并且正在注释测试类的testproject中,注释被忽略,并且不会编译任何代码。加载时间编织是否可能?

1 个答案:

答案 0 :(得分:0)

是的,可以使用LTW,但不能没有用户执行任何。至少她需要通过-javaagent:pathto/aspectjweaver.jar将编织代理放在JVM命令行上。

相关问题