Lookup Java enum by string value
Say I have an enum which is just
public enum Blah {
A, B, C, D
}
and I would like to find the enum value of a string, for example "A" which would be Blah.A . How would it be possible to do this?
Is the Enum.valueOf() the method I need? If so, how would I use this?
Yes, Blah.valueOf("A") will give you Blah.A .
Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException .
The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.
如果文本与枚举值不相同,则为另一种解决方案:
public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");
private String text;
Blah(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Blah fromString(String text) {
for (Blah b : Blah.values()) {
if (b.text.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
链接地址: http://www.djcxy.com/p/992.html
上一篇: 抽象函数和虚函数之间有什么区别?
下一篇: 通过字符串值查找Java枚举
