簡體   English   中英

在每個注解的構造函數之后自動設置屬性

[英]Automatically set attribute after constructor per annotation

我有一堂課。 像這樣:

public class Example {
  public Example() {
    System.out.println("Constructor");
  }
}

現在我想擁有一個屬性“ Version”,該屬性在構造后會自動給出。 是否可以按批注解決它? 最好的解決方案是,如果我可以在某些類上方編寫@VersionControl之類的注釋,然后另一個模塊為這些類設置屬性“版本”。

像這樣:

@VersionControl
public class Example {

  int version; //this should be set automatically

  public Example() {
    System.out.println("Constructor");
  }
}

可能嗎? 謝謝您的幫助!

我的注釋和aspectj解決方案:

注解:

@Target(ElementType.TYPE)
   public @interface MyAnnotation{
}

方面:

@Aspect
public class MyAspect {

  @Pointcut("execution((@MyAnnotation *).new(..))")
   public void bla() {
   }

  @After("bla()")
   public void after(JoinPoint joinPoint) {
    try {
     joinPoint.getTarget().getClass().getDeclaredField("version").set(joinPoint.getTarget(), VersionProvider.getVersion());
    } catch (IllegalAccessException | NoSuchFieldException e) {
      e.printStackTrace();
    }
  }
}

示例對象:

@MyAnnotation
public class Example {

 public long version;

 public long getDarwinVersion() {
    return version;
 }

}

在此解決方案中,將在調用帶注釋的類的構造函數之后設置版本。

暫無
暫無

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

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