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

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

问题描述

它说:


原始

primitive

String

一个枚举

另一个注释

以上任何一个数组

只有这些类型是合法的注释成员为什么一般的枚举不能是注释的成员?

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();

}

这是不允许的。但是枚举是不是常数吗?当您使用 @Param(XXX)时,填写枚举 @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)

我想要所有上述都合法。 p>

I want all above to be legal.

推荐答案

虽然每个枚举类型继承自 java。 lang.Enum ,类型枚举本身不是一个枚举类型。同样,当每个注释类型从 java.lang.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),你不能使用枚举常量来做同样的事情。您只能引用枚举类型中声明的常量,如 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 - 为什么是枚举< E>不允许作为注释成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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