i have a class. Something like this:
public class Example {
public Example() {
System.out.println("Constructor");
}
}
Now i want to have an attribute "Version" which is given automatically after construction. Is it possible to resolve it per annotation? The best solution would be, if i could write a annotation like @VersionControl above some classes and then another module sets an attribute "version" for the classes.
Something like this:
@VersionControl
public class Example {
int version; //this should be set automatically
public Example() {
System.out.println("Constructor");
}
}
Is it possible? Thx for your help!
My solution with annotation and aspectj:
Annotation:
@Target(ElementType.TYPE)
public @interface MyAnnotation{
}
Aspect:
@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();
}
}
}
Example object:
@MyAnnotation
public class Example {
public long version;
public long getDarwinVersion() {
return version;
}
}
In this solution, the version will be set after the constructor of the annotated class was called.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.