Reputation: 8241
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
Reputation: 81
Any one who is trying to fetch all the values as list can simply do this.
Arrays.asList(YouEnumClass.values())
Upvotes: 5
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
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
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
Reputation: 13828
Enum
s are just like Class
es 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
Reputation: 1401
YourEnumClass[] yourEnums = YourEnumClass.class.getEnumConstants();
Or
YourEnumClass[] yourEnums = YourEnumClass.values();
Upvotes: 130