簡體   English   中英

是否可以借助注釋將代碼編織到我自己的代碼之外?

[英]Is it possible to weave code outside my own code with the help of annotations?

我有一個主意,想知道,是否可能,如果可以,如何。 我正在為其他用戶設計一個圖書館,以簡化他們的生活。

我有兩個注釋。

達爾文:

@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 + '}';
 }
}

該代碼有效,但僅在我自己的項目中。 在包含達爾文庫並注釋測試類的測試項目中,注釋將被忽略,並且不會編織任何代碼。 加載時間編織是否可行?

是的,使用LTW可以實現,但是如果用戶沒有做任何事情 ,那是不可能的。 至少她需要通過-javaagent:pathto/aspectjweaver.jar將編織代理放置在JVM命令行上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM