問題描述
今天我想在 這個(gè)文檔之后創(chuàng)建我的第一個(gè)注釋接口 我得到了這個(gè)編譯器錯(cuò)誤
<塊引用>注解成員的類型無效":公共@interface MyAnnotation {對(duì)象我的參數(shù);^^^^^^}
顯然 Object
不能用作注解成員的類型.不幸的是,我找不到任何關(guān)于一般可以使用哪些類型的信息.
這是我通過反復(fù)試驗(yàn)發(fā)現(xiàn)的:
字符串
→ 有效int
→ 有效整數(shù)
→ 無效(令人驚訝)String[]
→ 有效(令人驚訝)對(duì)象
→ 無效
也許有人可以闡明哪些類型實(shí)際上是允許的以及為什么.
由JLS 的第 9.6.1 節(jié).注釋成員類型必須是以下之一:
- 原始
- 字符串
- 一個(gè)枚舉
- 另一個(gè)注解
- 類
- 上述任何一項(xiàng)的數(shù)組
它看起來確實(shí)有限制,但毫無疑問是有原因的.
還要注意多維數(shù)組(例如 String[][]
)被上述規(guī)則隱式禁止.
如 this answer 中所述,不允許使用 Class 數(shù)組.
Today I wanted to create my first annotation interface following this documentation and I got this compiler error
Invalid type for annotation member": public @interface MyAnnotation { Object myParameter; ^^^^^^ }
Obviously Object
cannot be used as type of an annotation member. Unfortunately I could not find any information on which types can be used in general.
This I found out using trial-and-error:
String
→ Validint
→ ValidInteger
→ Invalid (Surprisingly)String[]
→ Valid (Surprisingly)Object
→ Invalid
Perhaps someone can shed some light on which types are actually allowed and why.
It's specified by section 9.6.1 of the JLS. The annotation member types must be one of:
- primitive
- String
- an Enum
- another Annotation
- Class
- an array of any of the above
It does seem restrictive, but no doubt there are reasons for it.
Also note that multidimensional arrays (e.g. String[][]
) are implicitly forbidden by the above rule.
Arrays of Class are not allowed as described in this answer.
這篇關(guān)于Java注解成員可以使用哪些類型?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!