简体   繁体   English

Java - 为什么是Enum <E> 不允许作为注释成员?

[英]Java - Why is Enum<E> not allowed as Annotation member?

It says: 它说:

primitive 原始

String

Class

an Enum 一个枚举

another Annotation 另一个注释

an array of any of the above 上面任何一个的数组

Only these types are legal to be as Annotation member, why can't a generic Enum be a member of Annotation? 只有这些类型作为注释成员是合法的,为什么通用的Enum不能成为注释的成员?

For example : 例如 :

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

    Enum value();

}

This is not allowed. 这是不允许的。 But Enum is a constant isn't it? 但是Enum是一个常数不是吗? As you are using @Param(XXX) , filling in the Enum , the @Param(XXX) is decided (which means this is constant). 当您使用@Param(XXX) ,填写Enum ,将决定@Param(XXX) (这意味着它是常量)。 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. 我希望以上所有都是合法的。

While each enum type inherits from java.lang.Enum , the type Enum itself is not an enum type. 虽然每个enum类型都继承自java.lang.Enum ,但Enum类型本身不是enum类型。 Similarly, while every annotation type inherits from java.lang.annotation.Annotation , the type Annotation itself is not an annotation type. 类似地,虽然每个注释类型都继承自java.lang.annotation.Annotation ,但Annotation类型本身不是注释类型。

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. 因此,将注释属性声明为Object并动态发现实际值的类型是技术上可行的,但正式规范不允许这样做。

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"; 所以虽然你可以声明一个编译时常量,如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. 并在@Name(value=FOO)这样的注释中引用它,你不能对enum常量做同样的事情。 You can only refer to the constant as declared in the enum type itself like EnumType.NAME . 您只能引用enum类型本身声明的常量,如EnumType.NAME This also is a consequence of how it is formally defined in the specification. 这也是它在规范中如何正式定义的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM