Get enum value from enum type and ordinal

可紊 提交于 2019-12-30 08:39:05

问题


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

Assuming field.getType().isEnum() is true, how would I produce the enum value for the given ordinal?


回答1:


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

suffices. One line; straightforward enough.




回答2:


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];
}



回答3:


ExampleTypeEnum value = ExampleTypeEnum.values()[ordinal]


来源:https://stackoverflow.com/questions/13871532/get-enum-value-from-enum-type-and-ordinal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!