在 Java 中将 Int 转换为枚举 [英] Cast Int to enum in Java
本文介绍了在 Java 中将 Int 转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于以下枚举,在 Java 中将 Int 转换为枚举的正确方法是什么?
What is the correct way to cast an Int to an enum in Java given the following enum?
public enum MyEnum
{
EnumValue1,
EnumValue2
}
MyEnum enumValue = (MyEnum) x; //Doesn't work???
推荐答案
Try MyEnum.values()[x]
where x
must be 0
code> 或 1
,即该枚举的有效序数.
Try MyEnum.values()[x]
where x
must be 0
or 1
, i.e. a valid ordinal for that enum.
请注意,在 Java 中枚举实际上是类(因此枚举值是对象),因此您不能将 int
甚至 Integer
转换为枚举.
Note that in Java enums actually are classes (and enum values thus are objects) and thus you can't cast an int
or even Integer
to an enum.
这篇关于在 Java 中将 Int 转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文