Java 从枚举值获取枚举名称
我读过很多关于如何使用java从Java 从枚举值获取枚举名称,java,enums,Java,Enums,我读过很多关于如何使用java从enum的值中获取对应名称的文章,但是没有一个例子适合我!怎么了 公共类扩展{ 公共枚举关系ActiveEnum { 邀请(0), 主动(1), 暂停(2); 私有最终整数值; private RelationActiveEnum(最终整数值){ 这个值=值; } } } 在另一类中,我使用: int dbValue=supp.ACTIVE; Extensions.RelationActiveEnum枚举值(dbValue); 字符串stringName=enu
enum
的值中获取对应名称的文章,但是没有一个例子适合我!怎么了
公共类扩展{
公共枚举关系ActiveEnum
{
邀请(0),
主动(1),
暂停(2);
私有最终整数值;
private RelationActiveEnum(最终整数值){
这个值=值;
}
}
}
在另一类中,我使用:
int dbValue=supp.ACTIVE;
Extensions.RelationActiveEnum枚举值(dbValue);
字符串stringName=enumValue.toString()//看得见的
//或
int dbValuee=支持活动;
String stringValue=Enum.GetName(typeof(RelationActiveEnum),dbValue);
我应该工作,对吗?但事实并非如此!!!!它告诉我dbValue不能强制转换为RelationActiveEnum…您可以做的是
RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
RelationActiveEnum.ACTIVE.name();
或
或
如果要按枚举的字段进行查找,则需要构造一个集合,如列表、数组或映射
public enum RelationActiveEnum {
Invited(0),
Active(1),
Suspended(2);
private final int code;
private RelationActiveEnum(final int code) {
this.code = code;
}
private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
static {
for (RelationActiveEnum rae : RelationActiveEnum.values()) {
BY_CODE_MAP.put(rae.code, rae);
}
}
public static RelationActiveEnum forCode(int code) {
return BY_CODE_MAP.get(code);
}
}
假设我们有:
public enum MyEnum {
Test1, Test2, Test3
}
要获取枚举变量的名称,请使用:
要从(字符串)名称获取枚举,请使用:
如果需要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: MyEunm.values()) {
if(e.value == value) {
return e;
}
}
return null;// not found
}
由于您的“值”也恰好与序数匹配,您只需执行以下操作:
public enum RelationActiveEnum {
Invited,
Active,
Suspended;
private final int value;
private RelationActiveEnum() {
this.value = ordinal();
}
}
以及从值中获取枚举:
int value = 1;
RelationActiveEnum enumInstance = RelationActiveEnum.values()[value];
我想静态方法将是一个很好的地方:
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);
}
}
}
显然,如果您的“值”与枚举序号的值不同,这一切都会崩溃。您可以创建一个查找方法。不是最有效的(取决于枚举的大小),但它可以工作
public static String getNameByCode(int code){
for(RelationActiveEnum e : RelationActiveEnum.values()){
if(code == e.value) return e.name();
}
return null;
}
这样称呼它:
RelationActiveEnum.getNameByCode(3);
若您希望在运行时条件下更高效,可以使用一个映射,该映射包含枚举的所有可能选项(按其值)。但在初始化JVM时速度会慢一些
import java.util.HashMap;
import java.util.Map;
/**
* Example of enum with a getter that need a value in parameter, and that return the Choice/Instance
* of the enum which has the same value.
* The value of each choice can be random.
*/
public enum MyEnum {
/** a random choice */
Choice1(4),
/** a nother one */
Choice2(2),
/** another one again */
Choice3(9);
/** a map that contains every choices of the enum ordered by their value. */
private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
static {
// populating the map
for (MyEnum myEnum : values()) {
MY_MAP.put(myEnum.getValue(), myEnum);
}
}
/** the value of the choice */
private int value;
/**
* constructor
* @param value the value
*/
private MyEnum(int value) {
this.value = value;
}
/**
* getter of the value
* @return int
*/
public int getValue() {
return value;
}
/**
* Return one of the choice of the enum by its value.
* May return null if there is no choice for this value.
* @param value value
* @return MyEnum
*/
public static MyEnum getByValue(int value) {
return MY_MAP.get(value);
}
/**
* {@inheritDoc}
* @see java.lang.Enum#toString()
*/
public String toString() {
return name() + "=" + value;
}
/**
* Exemple of how to use this class.
* @param args args
*/
public static void main(String[] args) {
MyEnum enum1 = MyEnum.Choice1;
System.out.println("enum1==>" + String.valueOf(enum1));
MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
MyEnum enum3Unknown = MyEnum.getByValue(4);
System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
}
}
import java.util.HashMap;
导入java.util.Map;
/**
*带有getter的枚举示例,该getter需要参数中的值,并返回选项/实例
*具有相同值的枚举的。
*每个选项的值可以是随机的。
*/
公共枚举髓鞘{
/**随机选择*/
选择1(4),
/**另一个*/
选择2(2),
/**再来一个*/
选择3(9);
/**包含按值排序的枚举的每个选项的映射*/
私有静态最终映射MY_Map=new HashMap();
静止的{
//填充地图
对于(MyEnum MyEnum:values()){
MY_MAP.put(myEnum.getValue(),myEnum);
}
}
/**选择的价值*/
私有int值;
/**
*建造师
*@param value这个值
*/
私有MyEnum(int值){
这个值=值;
}
/**
*价值的获取者
*@return int
*/
public int getValue(){
返回值;
}
/**
*按枚举值返回其中一个枚举选项。
*如果对此值没有选择,则可能返回null。
*@param值
*@return MyEnum
*/
公共静态MyEnum getByValue(int值){
返回MY_MAP.get(值);
}
/**
*{@inheritardoc}
*@see java.lang.Enum#toString()
*/
公共字符串toString(){
返回name()+“=”+值;
}
/**
*如何使用该类的示例。
*@param args args
*/
公共静态void main(字符串[]args){
MyEnum enum1=MyEnum.Choice1;
System.out.println(“enum1==>”+String.valueOf(enum1));
MyEnum enum2GotByValue=MyEnum.getByValue(enum1.getValue());
System.out.println(“enum2GotByValue==>”+String.valueOf(enum2GotByValue));
MyEnum3Unknown=MyEnum.getByValue(4);
System.out.println(“enum3Unknown==>”+String.valueOf(enum3Unknown));
}
}
在我的例子中,值不是整数而是字符串。
可以将getNameByCode方法添加到枚举以获取字符串值的名称-
enum CODE {
SUCCESS("SCS"), DELETE("DEL");
private String status;
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status
* the status to set
*/
public void setStatus(String status) {
this.status = status;
}
private CODE(String status) {
this.status = status;
}
public static String getNameByCode(String code) {
for (int i = 0; i < CODE.values().length; i++) {
if (code.equals(CODE.values()[i].status))
return CODE.values()[i].name();
}
return null;
}
enum代码{
成功(“SCS”),删除(“DEL”);
私有字符串状态;
/**
*@返回状态
*/
公共字符串getStatus(){
返回状态;
}
/**
*@param状态
*要设置的状态
*/
公共无效设置状态(字符串状态){
这个状态=状态;
}
专用代码(字符串状态){
这个状态=状态;
}
公共静态字符串getNameByCode(字符串代码){
对于(int i=0;i
这是我对它的看法:
public enum LoginState {
LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);
private int code;
LoginState(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static LoginState getLoginStateFromCode(int code){
for(LoginState e : LoginState.values()){
if(code == e.code) return e;
}
return LoginState.LOGGED_OUT; //or null
}
};
我在安卓系统中使用过它,比如:
LoginState getLoginState(int i) {
return LoginState.getLoginStateFromCode(
prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
);
}
public static void setLoginState(LoginState newLoginState) {
editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
editor().commit();
}
其中
pref
和editor
是SharedReferences
和SharedReferences.editorsupp.ACTIVE或supp.ACTIVE?请确认:是否要获取给定int值的对应名称?即1-->ACTIVE
或ACTIVE-->1
?它是supp.ACTIVE,我从数据库中获取的值,t它可以是0,1或2…是的,我在网上搜索了java的例子,我读到了一些类似于这里发布的内容这可能是一个重复的谢谢你,非常简单,它工作了!!谢谢你,请注意差距…如果你的值不是序号…请查看@PeterLawrey的答案,并且在你的枚举上做一个静态方法,以防你改变你的想法:)鲍勃叔叔说使用序数是个坏主意。我同意这一点。@Piotr我怀疑叔叔指的是传递序数并保持它,这是一个好建议。使用名称或其他标识符。但是考虑到问题,这是你解决问题的方法。投票吧,因为在enum关系中并不总是位置ActiveEnum.values()[value]
表示它的值。这可能会有性能问题,因此我建议
RelationActiveEnum.getNameByCode(3);
import java.util.HashMap;
import java.util.Map;
/**
* Example of enum with a getter that need a value in parameter, and that return the Choice/Instance
* of the enum which has the same value.
* The value of each choice can be random.
*/
public enum MyEnum {
/** a random choice */
Choice1(4),
/** a nother one */
Choice2(2),
/** another one again */
Choice3(9);
/** a map that contains every choices of the enum ordered by their value. */
private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
static {
// populating the map
for (MyEnum myEnum : values()) {
MY_MAP.put(myEnum.getValue(), myEnum);
}
}
/** the value of the choice */
private int value;
/**
* constructor
* @param value the value
*/
private MyEnum(int value) {
this.value = value;
}
/**
* getter of the value
* @return int
*/
public int getValue() {
return value;
}
/**
* Return one of the choice of the enum by its value.
* May return null if there is no choice for this value.
* @param value value
* @return MyEnum
*/
public static MyEnum getByValue(int value) {
return MY_MAP.get(value);
}
/**
* {@inheritDoc}
* @see java.lang.Enum#toString()
*/
public String toString() {
return name() + "=" + value;
}
/**
* Exemple of how to use this class.
* @param args args
*/
public static void main(String[] args) {
MyEnum enum1 = MyEnum.Choice1;
System.out.println("enum1==>" + String.valueOf(enum1));
MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
MyEnum enum3Unknown = MyEnum.getByValue(4);
System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
}
}
enum CODE {
SUCCESS("SCS"), DELETE("DEL");
private String status;
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status
* the status to set
*/
public void setStatus(String status) {
this.status = status;
}
private CODE(String status) {
this.status = status;
}
public static String getNameByCode(String code) {
for (int i = 0; i < CODE.values().length; i++) {
if (code.equals(CODE.values()[i].status))
return CODE.values()[i].name();
}
return null;
}
public enum LoginState {
LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);
private int code;
LoginState(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static LoginState getLoginStateFromCode(int code){
for(LoginState e : LoginState.values()){
if(code == e.code) return e;
}
return LoginState.LOGGED_OUT; //or null
}
};
LoginState getLoginState(int i) {
return LoginState.getLoginStateFromCode(
prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
);
}
public static void setLoginState(LoginState newLoginState) {
editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
editor().commit();
}