我想以编译安全的形式使用Annotation.
要将value()传递给Annotation,我想使用枚举的String表示.
有没有办法将@A与枚举E中的值一起使用?
public class T {
public enum E {
a,b;
}
// C1: i want this, but it won't compile
@A(E.a)
void bar() {
// C2: no chance, it won't compile
@A(E.a.toString())
void bar2() {
}
// C3: this is ok
@A("a"+"b")
void bar3() {
}
// C4: is constant like C3, is'nt it ?
@A(""+E.a)
void bar4() {
}
}
@interface A {
String value();
}
Run Code Online (Sandbox Code Playgroud)
更新
我需要@A中的String类型.
关键是我能做到这一点
@A("" + 1)
void foo() {
}
Run Code Online (Sandbox Code Playgroud)
但这里编译器声称"属性值必须是常量".Is'nt Ea不变吗?
@A("" + E.a)
void foo() {
}
Run Code Online (Sandbox Code Playgroud)
lee*_*777 10
问题是你比编译器更聪明:-)
E.a是一个常数,但E.a.toString()不是.它看起来应该是,但编译器无法弄明白.
原因"a"+"b"和"" + 1工作原因是编译器足够聪明,可以在编译时生成常量.
当它看到时"" + E.a,它会使用E.a.toString().打电话toString()就足以将其抛弃.
E必须是枚举吗?你可以尝试:
public final class E {
public static final String a = "a";
public static final String b = "b";
};
Run Code Online (Sandbox Code Playgroud)
在E类型的注释中创建值:
@interface A {
E value();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用
@A(E.a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5576 次 |
| 最近记录: |