下面是一個根據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());
-
}
注意:建議優先使用第一種。
原文地址:https://blog.csdn.net/en_joker/article/details/85044179