Java - 为什么是 Enum<E>不允许作为注释成员? [英] Java - Why is Enum<E> not allowed as Annotation member?

查看:35
本文介绍了Java - 为什么是 Enum<E>不允许作为注释成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它说:

原始

字符串

一个枚举

另一个注解

上述任何一个的数组

只有这些类型才可以作为 Annotation 的成员,为什么泛型的 Enum 不能成为 Annotation 的成员?

Only these types are legal to be as Annotation member, why can't a generic Enum be a member of Annotation?

例如:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Param {

    Enum value();

}

这是不允许的.但是 Enum 是一个常量不是吗?当你使用@Param(XXX)时,填写Enum@Param(XXX)就确定了(这意味着这是常数).为什么只允许特定的枚举成为成员?

This is not allowed. But Enum is a constant isn't it? As you are using @Param(XXX), filling in the Enum, the @Param(XXX) is decided (which means this is constant). Why is it only a specific enum allowed to be a member?

我想做的是制作一个接收任何枚举的注释:

What I am trying to do is to make a Annotation that receives any enums:

// for example
@Param(value = AEnum.ABC)
@Param(value = BEnum.TTT)
@Param(value = CEnum.OOO)

我希望以上所有内容都是合法的.

I want all above to be legal.

推荐答案

虽然每个 enum 类型都继承自 java.lang.Enum,但类型 Enum 本身不是 enum 类型.类似地,虽然每个注解类型都继承自 java.lang.annotation.Annotation,但类型 Annotation 本身并不是注解类型.

While each enum type inherits from java.lang.Enum, the type Enum itself is not an enum type. Similarly, while every annotation type inherits from java.lang.annotation.Annotation, the type Annotation itself is not an annotation type.

这没有技术原因,在类文件中,每个实际值都会包含对其类型的引用.因此,将注解属性声明为 Object 并动态发现实际值的类型在技术上是可能的,但这在正式规范中是不允许的.

There is no technical reason for this, in the class file, each actual value will contain a reference to its type. So it would be technical possible to declare an annotation attribute as Object and discover the types of the actual values dynamically, but that’s not allowed by the formal specification.

顺便说一下,枚举常量也不是编译时常量.因此,虽然您可以声明像 final String FOO = "some string"; 这样的编译时常量,并在像 @Name(value=FOO) 这样的注释中引用它,你不能用 enum 常量做同样的事情.您只能引用在 enum 类型本身中声明的常量,如 EnumType.NAME.这也是规范中正式定义的结果.

By the way, enum constants also are not compile-time constants. So while you can declare a compile-time constant like final String FOO = "some string"; and refer to it in an annotation like @Name(value=FOO), you can’t do the same with an enum constant. You can only refer to the constant as declared in the enum type itself like EnumType.NAME. This also is a consequence of how it is formally defined in the specification.

这篇关于Java - 为什么是 Enum<E>不允许作为注释成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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