哪些类型可用于 Java 注释成员? [英] Which types can be used for Java annotation members?

查看:34
本文介绍了哪些类型可用于 Java 注释成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我想按照本文档创建我的第一个注释界面 我得到了这个编译器错误

<块引用>

注解成员类型无效":公共@interface MyAnnotation {对象 myParameter;^^^^^^}

显然 Object 不能用作注释成员的类型.不幸的是,我找不到任何关于一般可以使用哪些类型的信息.

这是我通过反复试验发现的:

  • String → 有效
  • int → 有效
  • Integer → 无效(令人惊讶)
  • String[] → 有效(令人惊讶)
  • 对象 → 无效

也许有人可以阐明实际允许的类型以及原因.

解决方案

JLS 第 9.6.1 节.注释成员类型必须是以下之一:

  • 原始
  • 字符串
  • 枚举
  • 另一个注释
  • 班级
  • 上述任何一项的数组

看起来确实有限制,但毫无疑问是有原因的.

另请注意,多维数组(例如 String[][])被上述规则隐式禁止.

此答案中所述,不允许使用类数组.

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 → Valid
  • int → Valid
  • Integer → 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 注释成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆