[英]Java Enum with field of type enum
Not sure how to phrase the question so please feel free to update it.不知道如何表述这个问题,所以请随时更新它。 I have a complex enumeration which references other enumerations based on the enumeration value, like this:我有一个复杂的枚举,它根据枚举值引用其他枚举,如下所示:
public enum EFormSw {
OBJ_KEY_LIST("Object Keys", EObjKeyType.class),
OBJ_NOTE_LIST("Object Notes", EObjNoteType.class);
public final String label;
public final Class</*"E is an Enum"*/> enumType;
// Constructor...
What I want to be able to do in another class is to write something like我希望能够在另一堂课上做的是写一些类似的东西
EFormSw.OBJ_KEY_LIST.enumType.values().someThingElse().
Which is only possible if its clear by the field type that this is an enumeration.这只有在字段类型清楚这是一个枚举时才有可能。
Is there any way to achieve this at all?有什么方法可以实现这一目标吗?
You can make enumType
a Class<? extends Enum<?>>
您可以使enumType
成为Class<? extends Enum<?>>
Class<? extends Enum<?>>
: Class<? extends Enum<?>>
:
enum EFormSw {
OBJ_KEY_LIST("Object Keys", EObjKeyType.class),
OBJ_NOTE_LIST("Object Notes", EObjNoteType.class);
private final String label;
private final Class<? extends Enum<?>> enumType;
EFormSw(String label, Class<? extends Enum<?>> enumType) {
this.label = label;
this.enumType = enumType;
}
public String getLabel() {
return label;
}
public Class<? extends Enum<?>> getEnumType() {
return enumType;
}
}
When you are looping through the values of EFormSw
, you can use getEnumConstants
to get an Enum<?>[]
representing the enum values of the enum type, but you won't be able to do much with it, because you don't know which exact enum type it is:当您遍历EFormSw
的值时,您可以使用getEnumConstants
来获取一个Enum<?>[]
表示枚举类型的枚举值,但您将无法使用它做太多事情,因为您没有知道它是哪种确切的枚举类型:
for (EFormSw constant: EFormSw.values()) {
Enum<?>[] values = constant.getEnumType().getEnumConstants();
}
(You can still call most of the methods declared in java.lang.Enum
and java.lang.Object
on the array elements, so if that's all you need, you can just use that.) (您仍然可以在数组元素上调用java.lang.Enum
和java.lang.Object
声明的大多数方法,因此如果您只需要这些,您就可以使用它。)
If you want to use some common functionality shared between EObjKeyType
and EObjNoteType
, you can extract all the common functionality into a common interface that they both implement:如果您想使用EObjKeyType
和EObjNoteType
之间共享的一些通用功能,您可以将所有通用功能提取到它们都实现的通用接口中:
interface EObjType {
// ...
}
enum EObjKeyType implements EObjType {
// ...
}
enum EObjNoteType implements EObjType {
// ...
}
Then change enumType
to:然后将enumType
更改为:
private final Class<? extends EObjType > enumType;
Now you can get a EObjType[]
instead.现在你可以得到一个EObjType[]
来代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.