假设我有一个枚举
public enum Blah {
A, B, C, D
}
我想找到一个字符串的枚举值,例如“a”,它将是Blah.a。如何做到这一点?
Enum.valueOf()是我需要的方法吗?如果是,我将如何使用它?
假设我有一个枚举
public enum Blah {
A, B, C, D
}
我想找到一个字符串的枚举值,例如“a”,它将是Blah.a。如何做到这一点?
Enum.valueOf()是我需要的方法吗?如果是,我将如何使用它?
当前回答
另一种实现方法是使用Enum的隐式静态方法name()。name将返回用于创建枚举的确切字符串,该枚举可用于对照提供的字符串进行检查:
public enum Blah {
A, B, C, D;
public static Blah getEnum(String s){
if(A.name().equals(s)){
return A;
}else if(B.name().equals(s)){
return B;
}else if(C.name().equals(s)){
return C;
}else if (D.name().equals(s)){
return D;
}
throw new IllegalArgumentException("No Enum specified for this string");
}
}
测试:
System.out.println(Blah.getEnum("B").name());
// It will print B B
灵感:Java中Enum的10个示例
其他回答
下面是我使用的一个漂亮的实用程序:
/**
* 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行。
太糟糕了,因为t被删除,我不能对Enum.valueOf使用t.class。
如果文本与枚举值不同,则另一种解决方案:
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;
}
}
最好使用Blah.valueOf(字符串),但也可以使用Enum.valueOf(Blah.class,字符串)。
你也应该小心处理你的案子。让我解释一下:Blah.valueOf(“A”)有效,但Blah.valueOf(“A”)无效。然后Blah.valueOf(“a”.toUpperCase(Locale.ENGLISH))也会起作用。
在Android上,你应该使用Locale.US,正如苏拉指出的那样。
一种O(1)方法,灵感来自Thrift生成的代码,该代码使用哈希图。
public enum USER {
STUDENT("jon",0),TEACHER("tom",1);
private static final Map<String, Integer> map = new HashMap<>();
static {
for (USER user : EnumSet.allOf(USER.class)) {
map.put(user.getTypeName(), user.getIndex());
}
}
public static int findIndexByTypeName(String typeName) {
return map.get(typeName);
}
private USER(String typeName,int index){
this.typeName = typeName;
this.index = index;
}
private String typeName;
private int index;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}