The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.
Object[] possibleValues = enumValue.getDeclaringClass().getEnumConstants();
YourEnumClass[] yourEnums = YourEnumClass.class.getEnumConstants();
Or
YourEnumClass[] yourEnums = YourEnumClass.values();
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
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.
... or MyEnum.values() ? Or am I missing something?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With