我想在編譯安全的表單中使用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();
}
更新
我需要@A String類型。
的一點是我可以做到這一點
@A("" + 1)
void foo() {
}
但這裏的編譯器索賠「的屬性值必須是常量」。 Is'nt E.a不變?
@A("" + E.a)
void foo() {
}
「E必須是一個枚舉嗎?你可以試試:......」我認爲你也可以用enums做類似的事情。你必須在'E'的構造函數中傳入你想要的字符串,然後將它分配給'public final String strRepresentation'。然後只要做@A(E.strRepresentation)' – MatrixFrog 2010-03-28 04:47:27
@MatrixFrog即使我把'public final String strRepresentation =「foo」;'放在E上,我得到'屬性值必須是常量' – leedm777 2010-03-28 04:55:33