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注解成员可以使用哪些类型?


- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01