我已经阅读了很多关于如何使用 java 从 enum
的值中获取相应名称的信息,但似乎没有一个示例对我有用!怎么了?
public class Extensions {
public enum RelationActiveEnum
{
Invited(0),
Active(1),
Suspended(2);
private final int value;
private RelationActiveEnum(final int value) {
this.value = value;
}
}
}
在我使用的另一个类中:
int dbValue = supp.ACTIVE;
Extensions.RelationActiveEnum enumValue(dbValue);
String stringName = enumValue.toString(); //Visible
// OR
int dbValuee = supp.ACTIVE;
String stringValue = Enum.GetName(typeof(RelationActiveEnum), dbValue);
我应该工作,对吧?但它没有!!!!它告诉我 dbValue 不能转换为 RelationActiveEnum...
最佳答案
假设我们有:
public enum MyEnum {
Test1, Test2, Test3
}
要获取枚举变量的名称,请使用 name()
:
MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"
要从(字符串)名称中获取枚举,请使用 valueOf()
:
String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);
如果您需要 integer
值来匹配枚举字段,请扩展枚举类:
public enum MyEnum {
Test1(1), Test2(2), Test3(3);
public final int value;
MyEnum(final int value) {
this.value = value;
}
}
现在你可以使用了:
MyEnum e = MyEnum.Test1;
int value = e.value; // = 1
并使用整数值查找枚举:
MyEnum getValue(int value) {
for(MyEnum e: MyEnum.values()) {
if(e.value == value) {
return e;
}
}
return null;// not found
}
关于java - 从枚举值中获取枚举名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319232/