假设我有一个枚举,它只是
public enum Blah {
A, B, C, D
}我想要查找字符串的枚举值,例如将为Blah.A的"A"。怎么可能做到这一点呢?
Enum.valueOf()是我需要的方法吗?如果是这样,我该如何使用它呢?
发布于 2010-06-03 18:57:50
如果文本与枚举值不同,另一种解决方案:
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;
}
}发布于 2009-11-12 23:52:49
下面是我使用的一个很棒的实用程序:
/**
* A common method for all enums since they can't have another base class
* @param <T> Enum type
* @param c enum type. All enums must be all caps.
* @param string case insensitive
* @return corresponding enum, or null
*/
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
if( c != null && string != null ) {
try {
return Enum.valueOf(c, string.trim().toUpperCase());
} catch(IllegalArgumentException ex) {
}
}
return null;
}然后在我的enum类中,我通常会这样做,以节省一些输入:
public static MyEnum fromString(String name) {
return getEnumFromString(MyEnum.class, name);
}如果您的枚举不都是大写的,只需更改Enum.valueOf行。
太糟糕了,我不能为Enum.valueOf使用T.class,因为T被擦除了。
发布于 2009-05-09 16:33:36
你也应该小心处理你的案例。让我解释一下:做Blah.valueOf("A")可以工作,但是Blah.valueOf("a")不能工作。然后,Blah.valueOf("a".toUpperCase(Locale.ENGLISH))又可以工作了。
在安卓系统中,你应该以sulai points out的身份使用Locale.US。
https://stackoverflow.com/questions/604424
复制相似问题