[英]Java: how to set default value to annotation with another annotation as its attribute?
[英]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.