Roman
Roman

Reputation: 8241

How to get all enum values in Java?

I came across this problem that I without knowing the actual enum type I need to iterate its possible values.

if (value instanceof Enum){
   Enum enumValue = (Enum)value;
}

Any ideas how to extract from enumValue its possible values ?

Upvotes: 131

Views: 205543

Answers (7)

Nagarjun Nagesh
Nagarjun Nagesh

Reputation: 81

Any one who is trying to fetch all the values as list can simply do this.

Arrays.asList(YouEnumClass.values())

Upvotes: 5

ColinD
ColinD

Reputation: 110104

Call Class#getEnumConstants to get the enum’s elements (or get null if not an enum class).

Object[] possibleValues = enumValue.getDeclaringClass().getEnumConstants();

Upvotes: 183

David Lilljegren
David Lilljegren

Reputation: 1949

One can also use the java.util.EnumSet like this

@Test
void test(){
    Enum aEnum =DayOfWeek.MONDAY;
    printAll(aEnum);
}

void printAll(Enum value){
    Set allValues = EnumSet.allOf(value.getClass());
    System.out.println(allValues);
}

Upvotes: 6

Ashwani Sharma
Ashwani Sharma

Reputation: 499

Here, Role is an enum which contains the following values [ADMIN, USER, OTHER].

List<Role> roleList = Arrays.asList(Role.values());
roleList.forEach(role -> {
    System.out.println(role);
    });

Upvotes: 7

RodeoClown
RodeoClown

Reputation: 13828

Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

You can do it like so:

enumValue.getDeclaringClass().getEnumConstants() 

This will return an array of Enum objects, with each being one of the available options.

Upvotes: 16

someone
someone

Reputation: 1401

YourEnumClass[] yourEnums = YourEnumClass.class.getEnumConstants();

Or

YourEnumClass[] yourEnums = YourEnumClass.values();

Upvotes: 130

deleted
deleted

Reputation: 195

... or MyEnum.values() ? Or am I missing something?

Upvotes: 9

Related Questions