2014-11-25 59 views
0

我有一个类。这样的事情:每个注释在构造函数后自动设置属性

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

现在我想要一个属性“版本”,它是在施工后自动给出。是否有可能根据注释解决它?最好的解决方案是,如果我可以在某些类上面编写像@VersionControl这样的注释,然后另一个模块为这些类设置属性“版本”。

事情是这样的:

@VersionControl 
public class Example { 

    int version; //this should be set automatically 

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

这可能吗? Thx为您提供帮助!

+0

当然。查看允许字节码重写的AspectJ或库。但就目前而言,您的问题非常广泛,可能不适合SO。 – 2014-11-25 12:08:45

+0

感谢您的评论。我将看看AspectJ并尝试自己回答我的问题。 – mrclrchtr 2014-11-25 13:37:11

回答

0

我与注释和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; 
} 

} 

在这种解决方案中,versio n将在注释类的构造函数被调用后设置。

相关问题