Get enumeration value from enumeration type and serial number

public <E extends Enum> E decode(java.lang.reflect.Field field, int ordinal) { // TODO } 

Assuming field.getType().isEnum() is true , how would I produce an enum value for a given sequence number?

+7
source share
3 answers
 field.getType().getEnumConstants()[ordinal] 

enough. One line; simple enough.

+15
source

To get what you want, you need to call YourEnum.values()[ordinal] . You can do this with reflection as follows:

 public static <E extends Enum<E>> E decode(Field field, int ordinal) { try { Class<?> myEnum = field.getType(); Method valuesMethod = myEnum.getMethod("values"); Object arrayWithEnumValies = valuesMethod.invoke(myEnum); return (E) Array.get(arrayWithEnumValies, ordinal); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } return null; } 

UPDATE

As @LouisWasserman noted in his comment, a much simpler way

 public static <E extends Enum<E>> E decode(Field field, int ordinal) { return (E) field.getType().getEnumConstants()[ordinal]; } 
+3
source
 ExampleTypeEnum value = ExampleTypeEnum.values()[ordinal] 
+2
source

All Articles