90

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.

2
  • its static - reflection. Commented Oct 26, 2009 at 19:40
  • Class is a reflection object (it predates the package). Commented Oct 26, 2009 at 19:56

4 Answers 4

173

Class.getEnumConstants

Sign up to request clarification or add additional context in comments.

Comments

27

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

Comments

19

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

1 Comment

It looks like this method is going to be way faster. The reflection method clones a shared array that's built using reflection and the security API. The EnumSet uses a "bit vector" stored in a long.
16

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.