如何在注释中使用数组常量

Tho*_*ung 48 java annotations

我想将常量用于注释值.

interface Client {

    @Retention(RUNTIME)
    @Target(METHOD)
    @interface SomeAnnotation { String[] values(); }

    interface Info {
        String A = "a";
        String B = "b";
        String[] AB = new String[] { A, B };
    }

    @SomeAnnotation(values = { Info.A, Info.B })
    void works();

    @SomeAnnotation(values = Info.AB)
    void doesNotWork();
}
Run Code Online (Sandbox Code Playgroud)

常数Info.AInfo.B可以在注释中使用,但不是数组Info.AB,因为它必须是在这个地方数组初始化.注释值仅限于可以内联到类的字节代码中的值.这对于数组常量是不可能的,因为它必须在Info加载时构造.这个问题有解决方法吗?

Tho*_*ung 44

不,没有解决方法.

  • @JensSchauder注释在编译时处理,因此甚至在代码运行之前.所以数组`AB`还不存在. (7认同)
  • 如果编译器希望将“数组初始值设定项”传递给注解,则声明一个编译时常量,如`private static final String[] AB = { ... };` 应该可以。据了解,Annotation 处理发生在实际编译之前,但随后错误信息并不准确。 (3认同)

ama*_*ion 14

为什么不将注释值设为枚举,这是您想要的实际数据值的关键?

例如

enum InfoKeys
{
 A("a"),
 B("b"),
 AB(new String[] { "a", "b" }),

 InfoKeys(Object data) { this.data = data; }
 private Object data;
}

@SomeAnnotation (values = InfoKeys.AB)
Run Code Online (Sandbox Code Playgroud)

这可以改进类型安全,但你明白了.

  • +1很好的想法.编译的例子会更好;-) (4认同)

Mic*_*uff 5

It is because arrays' elements can be changed at runtime (Info.AB[0] = "c";) while the annotation values are constant after compile time.

With that in mind someone will inevitably be confused when they try to change an element of Info.AB and expect the annotation's value to change (it won't). And if the annotation value were allowed to change at runtime it would differ than the one used at compile time. Imagine the confusion then!

(这里的混淆意味着有人可能会发现一个错误并花费数小时进行调试。)