問題描述
今天我想在 這個文檔之后創建我的第一個注釋接口 我得到了這個編譯器錯誤
<塊引用>注解成員的類型無效":公共@interface MyAnnotation {對象我的參數;^^^^^^}
顯然 Object
不能用作注解成員的類型.不幸的是,我找不到任何關于一般可以使用哪些類型的信息.
這是我通過反復試驗發現的:
字符串
→ 有效int
→ 有效整數
→ 無效(令人驚訝)String[]
→ 有效(令人驚訝)對象
→ 無效
也許有人可以闡明哪些類型實際上是允許的以及為什么.
由JLS 的第 9.6.1 節.注釋成員類型必須是以下之一:
- 原始
- 字符串
- 一個枚舉
- 另一個注解
- 類
- 上述任何一項的數組
它看起來確實有限制,但毫無疑問是有原因的.
還要注意多維數組(例如 String[][]
)被上述規則隱式禁止.
如 this answer 中所述,不允許使用 Class 數組.
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.
這篇關于Java注解成員可以使用哪些類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!