枚举类类型的变量 [英] Variable of type of enum class
问题描述
我需要将一个Enum类指定为另一个Enum中的类变量,如下所示:
I need to specify an Enum class as a class variable in another Enum like so:
enum A {}
enum B {
Class<Enum> clazz;
}
这样,贵族可以指向任何枚举类,例如A或B或任何其他类.可以用Java做到吗?
So that clazz can point to any Enum class like A or B or any other. Is it possible to do it in Java?
推荐答案
tl; dr
声明一个成员字段:
tl;dr
Declare a member field:
public Class< ? extends Enum > clazz ;
详细信息
显然是的,您可以将枚举 Class
对象保留为另一个枚举的类定义上的成员字段.
Details
Apparently yes, you can hold a enum Class
object as a member field on another enum’s class definition.
在此示例代码中,我们定义了自己的枚举 Animal
,其中提供了两个命名实例.我们的枚举包含一个 Class
类型的成员字段.在该成员字段中,我们存储传递给构造函数的两个枚举类之一.我们传递在 java.time 包 Month
.
In this example code we define our own enum, Animal
, providing for two named instances. Our enum carries a member field of type Class
. In that member field, we store either of two enum classes passed to the constructor. We pass enum classes defined in the java.time package, DayOfWeek
amd Month
.
enum Animal {
// Instances.
DOG( DayOfWeek.class ) , CAT( Month.class ) ;
// Member fields.
final public Class clazz ;
// Constructor
Animal( Class c ) {
this.clazz = c ;
}
}
访问该成员字段.
System.out.println( Animal.CAT.clazz.getCanonicalName() ) ;
在IdeOne.com上实时运行此代码.
Run this code live at IdeOne.com.
java.time.Month
java.time.Month
如果要限制成员字段仅包含碰巧是枚举的 Class
对象,请使用
If you want to restrict your member field to hold only Class
objects that happen to be enums, use Java Generics. Enums in Java are all, by definition, implicitly subclasses of Enum
.
enum Animal {
DOG( DayOfWeek.class ) , CAT( Month.class ) ;
final public Class< ? extends Enum > clazz ;
Animal( Class< ? extends Enum > c ) {
this.clazz = c ;
}
}
在上面的代码中,将 Month.class
更改为 ArrayList.class
,以获取编译器错误.我们声明我们的 clazz
成员字段包含一个 Class
对象,该对象表示一个类,该类是 Enum
的子类. Month
类确实是 Enum
的子类,而 ArrayList.class
不是.
In that code above, change the Month.class
to ArrayList.class
to get a compiler error. We declared our clazz
member field as holding a Class
object representing a class that is a subclass of Enum
. The Month
class is indeed a subclass of Enum
while ArrayList.class
is not.
使用泛型在IdeOne.com上运行该代码.
这篇关于枚举类类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!