下面是一个根据key值获取枚举类相应的value值的方法。
public static String getValue(String code) {
for (TestEnum ele : values()) {
if(ele.getCode().equals(code)) return ele.getValue();
}
return null;
}
枚举类
public enum Test {
A("Hello",0),B("World",1);
private String name;
private int code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
private Test(String name, int code) {
this.name = name;
this.code = code;
}
}
测试类
public static void main(String[] args) {
System.out.println(Enum.valueOf(Test.class,"A").getCode());
}
注意:建议优先使用第一种。
因篇幅问题不能全部显示,请点此查看更多更全内容