从枚举类型和序数中获取枚举值

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

假设field.getType().isEnum()true ,我将如何生成给定序数的枚举值?

 field.getType().getEnumConstants()[ordinal] 

就足够了。 一条线; 直截了当。

要获得你想要的东西,你需要调用YourEnum.values()[ordinal] 。 你可以用这样的reflection来做到这一点:

 public static > 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

正如@LouisWasserman在他的评论中指出的那样,有更简单的方法

 public static > E decode(Field field, int ordinal) { return (E) field.getType().getEnumConstants()[ordinal]; } 
 ExampleTypeEnum value = ExampleTypeEnum.values()[ordinal]