How to get all enum values in Java?
Solution 1
Call Class#getEnumConstants to get the enum’s elements (or get null if not an enum class).
Object[] possibleValues = enumValue.getDeclaringClass().getEnumConstants();
Solution 2
YourEnumClass[] yourEnums = YourEnumClass.class.getEnumConstants();
Or
YourEnumClass[] yourEnums = YourEnumClass.values();
Solution 3
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.
Solution 4
values method of enum
enum.values() method which returns all enum instances.
public class EnumTest {
private enum Currency {
PENNY("1 rs"), NICKLE("5 rs"), DIME("10 rs"), QUARTER("25 rs");
private String value;
private Currency(String brand) {
this.value = brand;
}
@Override
public String toString() {
return value;
}
}
public static void main(String args[]) {
Currency[] currencies = Currency.values();
// enum name using name method
// enum to String using toString() method
for (Currency currency : currencies) {
System.out.printf("[ Currency : %s,
Value : %s ]%n",currency.name(),currency);
}
}
}
http://javaexplorer03.blogspot.in/2015/10/name-and-values-method-of-enum.html
Solution 5
... or MyEnum.values() ? Or am I missing something?
Roman
If you need some help or advice in : Distributed system Cloud computing Very Large Datasets Everything that has any relations to Java and Jvms I might help :-)
Updated on January 19, 2022Comments
-
Roman 11 monthsI came across this problem that I without knowing the actual
enumtype 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 ?
-
ColinD almost 13 yearsYes, the actual class of the enum is not available here to make a static method call on, just an instance of some subtype of Enum. -
Peter Kriens almost 6 yearsWhy do you use the getDeclaringClass()? -
ColinD almost 6 years@PeterKriens: BecausegetClass()on anenumobject may return a subtype of theenumtype itself (if, say, theenumconstant overrides a method from theenumtype).getDeclaringClass()returns theenumtype that declared that constant, which is what you want here. -
Peter Kriens almost 6 yearsThanks! I had not realised that case but you are right, the constant can be of an anonymous inner class. -
zeratul021 over 2 yearsHowever, this is not generic. Question is about the case when only have the Enum object. So you need to either go via declaring class or better, via EnumSet.