Java 枚举:列出 Class<? 扩展枚举>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1626901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Enums: List enumerated values from a Class<? extends Enum>
提问by Landon Kuhn
I've got the class object for an enum (I have a Class<? extends Enum>
) and I need to get a list of the enumerated values represented by this enum. The values
static function has what I need, but I'm not sure how to get access to it from the class object.
我有一个枚举的类对象(我有一个Class<? extends Enum>
),我需要得到一个由这个枚举表示的枚举值的列表。该values
静态函数有我需要什么,但我不知道怎么去从类对象访问它。
采纳答案by Tom Hawtin - tackline
回答by dfa
using reflectionis simple as calling Class#getEnumConstants():
使用反射就像调用Class#getEnumConstants()一样简单:
List<Enum<?>> enum2list(Class<? extends Enum<?>> cls) {
return Arrays.asList(cls.getEnumConstants());
}
回答by Yishai
If you know the name of the value you need:
如果您知道所需值的名称:
Class<? extends Enum> klass = ...
Enum<?> x = Enum.valueOf(klass, "NAME");
If you don't, you can get an array of them by (as Tom got to first):
如果不这样做,您可以通过以下方式获取它们的数组(正如汤姆首先想到的那样):
klass.getEnumConstants();
回答by Magnilex
I am suprised to see that EnumSet#allOf()
is not mentioned:
我很惊讶地看到EnumSet#allOf()
没有提到:
public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)
Creates an enum set containing all of the elements in the specified element type.
public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)
创建一个枚举集,其中包含指定元素类型中的所有元素。
Consider the following enum
:
考虑以下几点enum
:
enum MyEnum {
TEST1, TEST2
}
Simply call the method like this:
只需像这样调用方法:
Set<MyEnum> allElementsInMyEnum = EnumSet.allOf(MyEnum.class);
Of course, this returns a Set
, not a List
, but it should be enough in many (most?) use cases.
当然,这返回 a Set
,而不是 a List
,但在许多(大多数?)用例中应该足够了。
Or, if you have an unknown enum
:
或者,如果您有一个未知的enum
:
Class<? extends Enum> enumClass = MyEnum.class;
Set<? extends Enum> allElementsInMyEnum = EnumSet.allOf(enumClass);
The advantage of this method, compared to Class#getEnumConstants()
, is that it is typed so that it is not possible to pass anything other than an enum
to it. For example, the below code is valid and returns null
:
与 相比,此方法的优点Class#getEnumConstants()
是它是类型化的,因此不可能向它传递除 an 之外的任何enum
内容。例如,以下代码有效并返回null
:
String.class.getEnumConstants();
While this won't compile:
虽然这不会编译:
EnumSet.allOf(String.class); // won't compile