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

前端 未结 4 1308
栀梦
栀梦 2020-12-09 14:14

I\'ve got the class object for an enum (I have a Class) and I need to get a list of the enumerated values represented by this enum. The

4条回答
  •  攒了一身酷
    2020-12-09 15:07

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

    public static > EnumSet allOf(Class 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 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 enumClass = MyEnum.class;
    Set 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
    

提交回复
热议问题