从枚举值获取枚举名称 [英] get enum name from enum value
本文介绍了从枚举值获取枚举名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经阅读了很多关于如何使用java从其值中获取相应名称的枚举
,但没有任何示例似乎适用于我!有什么问题?
I've read a lot about how obtain the corresponding name of an enum
from its value using java, but no example seems to work for me! What is wrong?
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 ...
I should work, right? but it doesn't!!!! it tells me that dbValue cannote be cast to RelationActiveEnum...
推荐答案
由于你的价值也恰好与ordinals匹配可以这样做:
Since your 'value' also happens to match with ordinals you could just do:
public enum RelationActiveEnum {
Invited,
Active,
Suspended;
private final int value;
private RelationActiveEnum() {
this.value = ordinal();
}
}
从值获取枚举:
int value = 1;
RelationActiveEnum enumInstance = RelationActiveEnum.values()[value];
我想一个静态方法将是一个好的地方:
I guess an static method would be a good place to put this:
public enum RelationActiveEnum {
public static RelationActiveEnum fromValue(int value)
throws IllegalArgumentException {
try {
return RelationActiveEnum.values()[value]
} catch(ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Unknown enum value :"+ value);
}
}
}
显然这一切都分崩离析你的'值'与枚举序号不一样。
Obviously this all falls apart if your 'value' isn't the same value as the enum ordinal.
这篇关于从枚举值获取枚举名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文