java 从枚举类型和序号中获取枚举值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13871532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get enum value from enum type and ordinal
提问by Distortum
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?
假设field.getType().isEnum()
是true
,我将如何生成给定序数的枚举值?
回答by Louis Wasserman
field.getType().getEnumConstants()[ordinal]
suffices. One line; straightforward enough.
就够了。一条线; 够直接了。
回答by Pshemo
To get what you want you need to invoke YourEnum.values()[ordinal]
. You can do it with reflection like this:
要获得您想要的东西,您需要调用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;
}
UPDATE
更新
As @LouisWasserman pointed in his comment there is much simpler way
正如@LouisWasserman 在他的评论中指出的那样,有更简单的方法
public static <E extends Enum<E>> E decode(Field field, int ordinal) {
return (E) field.getType().getEnumConstants()[ordinal];
}
回答by AlexWien
ExampleTypeEnum value = ExampleTypeEnum.values()[ordinal]
回答by Sam Ginrich
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)