我想将常量用于注释值.
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.A
和Info.B
可以在注释中使用,但不是数组Info.AB
,因为它必须是在这个地方数组初始化.注释值仅限于可以内联到类的字节代码中的值.这对于数组常量是不可能的,因为它必须在Info
加载时构造.这个问题有解决方法吗?
Tho*_*ung 44
不,没有解决方法.
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)
这可以改进类型安全,但你明白了.
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!
(这里的混淆意味着有人可能会发现一个错误并花费数小时进行调试。)