2010-03-27 149 views
7

我想在編譯安全的表單中使用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() { 
} 

回答

9

的問題是,你比編譯:-)

更聰明

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"; 
}; 
+0

「E必須是一個枚舉嗎?你可以試試:......」我認爲你也可以用enums做類似的事情。你必須在'E'的構造函數中傳入你想要的字符串,然後將它分配給'public final String strRepresentation'。然後只要做@A(E.strRepresentation)' – MatrixFrog 2010-03-28 04:47:27

+0

@MatrixFrog即使我把'public final String strRepresentation =「foo」;'放在E上,我得到'屬性值必須是常量' – leedm777 2010-03-28 04:55:33

7

請在E型的標註值:

@interface A { 
    E value(); 
} 

然後你可以使用

@A(E.a)