Get enum value from enum type and ordinal

2020-03-17 02:59发布

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?

3条回答
Explosion°爆炸
2楼-- · 2020-03-17 03:33
field.getType().getEnumConstants()[ordinal]

suffices. One line; straightforward enough.

查看更多
三岁会撩人
3楼-- · 2020-03-17 03:33
ExampleTypeEnum value = ExampleTypeEnum.values()[ordinal]
查看更多
家丑人穷心不美
4楼-- · 2020-03-17 03:51

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];
}
查看更多
登录 后发表回答