简体   繁体   English

在每个注解的构造函数之后自动设置属性

[英]Automatically set attribute after constructor per annotation

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. 现在我想拥有一个属性“ Version”,该属性在构造后会自动给出。 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. 最好的解决方案是,如果我可以在某些类上方编写@VersionControl之类的注释,然后另一个模块为这些类设置属性“版本”。

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: 我的注释和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. 在此解决方案中,将在调用带注释的类的构造函数之后设置版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM