Which types can be used for Java annotation members?(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.
这篇关于Java注解成员可以使用哪些类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java注解成员可以使用哪些类型?


基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01