以动态方式提供的 Java 注释值 [英] Java Annotations values provided in dynamic manner

查看:29
本文介绍了以动态方式提供的 Java 注释值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to provide annotations with some values generated by some methods.

到目前为止我已经尝试过了:

I tried this so far:

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_NAMEstatic final,它抱怨

Thought GENERIC_GENERATED_NAME is static final, it complains that

注解属性MyInterface.aString的值必须是常量表达式

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

那么如何实现呢?

推荐答案

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

There is no way to dynamically generate a string used in an annotation. The compiler evaluates annotation metadata for RetentionPolicy.RUNTIME annotations at compile time, but GENERIC_GENERATED_NAME isn't known until runtime. And you can't use generated values for annotations that are RetentionPolicy.SOURCE because they are discarded after compile time, so those generated values would never be known.

这篇关于以动态方式提供的 Java 注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆