JavaEnums: 列出类 < ? 扩展 Enum > 中的枚举值

我已经得到了一个枚举的类对象(我有一个 Class<? extends Enum>) ,并且我需要得到这个枚举所表示的枚举值的列表。values静态函数有我需要的东西,但是我不确定如何从 class 对象访问它。

31655 次浏览

using reflection is simple as calling Class#getEnumConstants():

List<Enum<?>> enum2list(Class<? extends Enum<?>> cls) {
return Arrays.asList(cls.getEnumConstants());
}

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

I am suprised to see that EnumSet#allOf() is not mentioned:

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.

Consider the following 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.

Or, if you have an unknown 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:

String.class.getEnumConstants();

While this won't compile:

EnumSet.allOf(String.class); // won't compile