Java注释值以动态方式提供

我想为某些方法生成的某些值提供注释.

到目前为止我已经试过了

public @interface MyInterface {
    String aString();
}
@MyInterface(aString = MyClass.GENERIC_GENERATED_NAME)
public class MyClass {

    static final String GENERIC_GENERATED_NAME = MyClass.generateName(MyClass.class);

    public static final String generateName(final Class<?> c) {
        return c.getClass().getName();
    }
}

思想GENERIC_GENERATED_NAME是静态的最后,它抱怨

The value for annotation attribute MyInterface.aString must be a constant expression

那么如何实现呢?

解决方法

没有办法动态生成注释中使用的字符串.编译器在编译时评估RetentionPolicy.RUNTIME注释的注释元数据,但在运行时之前,GENERIC_GENERATED_NAME是不知道的.并且您不能为RetentionPolicy.soURCE注释使用生成的值,因为它们在编译时被丢弃,因此这些生成的值将永远不会被知道.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...