2016-01-23 86 views
1
public Class Constants { 
    public static final String single = "aabbcc"; 
    public static final String[] ttt = {"aa", "bb", "cc"}; 
} 

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.PARAMETER, ElementType.FIELD}) 
public @interface Anno { 
    String aaa() default "aaa"; //this is allowed. 
    String bbb() default Constants.single; //this is allowed. 
    String[] ccc() default {}; //this is also allowed. 
    String[] ddd() default Constants.ttt; //while this is not! 
} 

如上例所示,我不明白爲什麼字符串數組常量不允許作爲註釋屬性值?Java - 爲什麼數組常量不允許作爲Annotation屬性值?

+0

我不相信Java中有一個「數組常量」這個東西......你給出的語法是一個帶有運行時語義的「數組初始值設定器」。 –

+0

什麼是編譯器錯誤信息? –

回答

0

就像Jim Garrison在評論中提到的那樣,在Java中沒有像「數組常量」那樣的東西。

這是很容易證明,一個數組是不是一個常數:

// Right now, Constants.ttt contains {"aa", "bb", "cc"} 
Constants.ttt[1] = "foobar"; 
// Right now, Constants.ttt contains {"aa", "foobar", "cc"} 

因此,這與其說是String數組常量是不允許的,因爲有在Java中的String數組常量沒有這樣的事。

相關問題