Get enum value from enum type and ordinal

前端 未结 4 996
小蘑菇
小蘑菇 2021-01-12 08:09
public  E decode(java.lang.reflect.Field field, int ordinal) {
    // TODO
}

Assumin

相关标签:
4条回答
  • 2021-01-12 08:33
    ExampleTypeEnum value = ExampleTypeEnum.values()[ordinal]
    
    0 讨论(0)
  • 2021-01-12 08:38

    According to title, suggest

    public <E extends Enum> E decode(Class<?> enumType, int ordinal) 
    {
       return enumType.getEnumConstants()[ordinal];
    }
    

    to be called by

    YourEnum enumVal = decode(YourEnum.class, ordinal)
    
    0 讨论(0)
  • 2021-01-12 08:47

    To get what you want you need to invoke YourEnum.values()[ordinal]. You can do it with reflection like this:

    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 pointed in his comment there is much simpler way

    public static <E extends Enum<E>> E decode(Field field, int ordinal) {
        return (E) field.getType().getEnumConstants()[ordinal];
    }
    
    0 讨论(0)
  • 2021-01-12 08:49
    field.getType().getEnumConstants()[ordinal]
    

    suffices. One line; straightforward enough.

    0 讨论(0)
提交回复
热议问题