public <E extends Enum> E decode(java.lang.reflect.Field field, int ordinal) {
// TODO
}
假设
field.getType().isEnum()
为true
,我该如何生成给定序数的枚举值?public <E extends Enum> E decode(java.lang.reflect.Field field, int ordinal) {
// TODO
}
field.getType().isEnum()
为true
,我该如何生成给定序数的枚举值?field.getType().getEnumConstants()[ordinal]
足够了。一行;足够直接。
Field
和 Class
的范围内之外,xD - JaiExampleTypeEnum value = ExampleTypeEnum.values()[ordinal]
YourEnum.values()[ordinal]
。你可以使用反射来实现它,代码如下: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;
}
正如@LouisWasserman在他的评论中指出的那样,有更简单的方法。
public static <E extends Enum<E>> E decode(Field field, int ordinal) {
return (E) field.getType().getEnumConstants()[ordinal];
}
return (Enum[])field.getType().getMethod("values").invoke(null))[ordinal]
这样的操作。 - Steve<E extends Enum<E>>
。 - Bohemianfield.getType().getEnumConstants()[ordinal]
。 - Louis Wasserman根据标题,建议
public <E extends Enum> E decode(Class<?> enumType, int ordinal)
{
return enumType.getEnumConstants()[ordinal];
}
被调用
YourEnum enumVal = decode(YourEnum.class, ordinal)
Field
不是枚举类型。我已经更新了问题以澄清这一点,尽管我认为从标签中应该很明显。 - Steve