简体   繁体   中英

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?

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? 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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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