简体   繁体   English

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

[英]Java Enums: List enumerated values from a Class<? extends Enum>

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. 我有一个枚举的类对象(我有一个Class<? extends Enum> ),我需要得到这个枚举所代表的枚举值的列表。 The values static function has what I need, but I'm not sure how to get access to it from the class object. 静态函数values具有我需要的功能,但我不确定如何从类对象访问它。

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

using reflection is simple as calling Class#getEnumConstants() : 使用反射很简单,因为调用Class#getEnumConstants()

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

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. 创建一个包含指定元素类型中所有元素的枚举集。

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. 当然,这会返回一个Set ,而不是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. Class#getEnumConstants()相比,此方法的优点在于它是键入的,因此无法将enum以外的任何内容传递给它。 For example, the below code is valid and returns null : 例如,以下代码有效并返回null

String.class.getEnumConstants();

While this won't compile: 虽然这不会编译:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM