这个问题已经在这里有了答案: > Can I get an enum based on the value of its field? 3个
我有一个String定义如下的枚举
public enum MyEnumType {
PRIMARY("primary"),
SECONDARY("secondary");
private final String myEnumType;
MyEnumType(String myEnumType) {
this.myEnumType = myEnumType;
}
public boolean equalsType(String myOtherEnumType) {
return myOtherEnumType != null && myEnumType.equals(myOtherEnumType);
}
@Override
public String toString() {
return this.myEnumType;
}
}
当我在下面的字符串中定义枚举时
MyEnumType myEnumType = MyEnumType.valueOf("primary");
崩溃了
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant HelloWorld.MyEnumType.primary
at java.lang.Enum.valueOf(Enum.java:238)
at HelloWorld$MyEnumType.valueOf(HelloWorld.java:11)
at HelloWorld.main(HelloWorld.java:36)
我有想念吗?
最佳答案
您可以调用MyEnumType.valueOf(x.toUpperCase())使其查找大写版本.
例如
MyEnumType e = MyEnumValue.valueOf("primary".toUpperCase());
Is it possible that I have a way to provide Secondary-Style, and it get to instantiate the enum that I want, without need to manually manipulate the string?
您可以提供替代查找的映射.
static final Map<String, MyEnumType> altMap = new HashMap<>();
static {
for (MyEnumType met : MyEnumType.values()) {
altMap.put(met.myEnumType, met);
// add more aliases as desired.
}
}
public static MyEnumType lookup(String str) {
MyEnumType met = altMap.get(str);
return met == null ? valueOf(str) : met;
}