Java注解成员可以使用哪些类型?
今天我想在 这个文档之后创建我的第一个注释接口 我得到了这个编译器错误
<块引用>注解成员的类型无效":公共@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.
相关文章