我有一个这样定义的枚举:
private static enum COLOR {
BLACK(Color.BLACK,"Black"),
GREEN(Color.GREEN,"Green");
private Color color;
private String name;
COLOR(String n, Color c) {
this.name = n;
this.color = c;
}
我试图找到一种基于字符串(这是第二个附加参数)来获取枚举常量的方法。所以,对于一个完全假设的例子,Id做类似的事情
COLOR.getEnumFromString("Green")
答案 0 :(得分:3)
public static COLOR getEnumFromString(final String value) {
if (value == null) {
throw new IllegalArgumentException();
}
for (COLOR v : values()) {
if (value.equalsIgnoreCase(v.getValue())) {
return v;
}
}
throw new IllegalArgumentException();
}
答案 1 :(得分:0)
维护Map<String, COLOR>
并检查getEnumFromString
中的地图。我推荐如下内容:
public enum COLOR{
....
private static class MapWrapper{
private static final Map<String, COLOR> myMap = new HashMap<String, COLOR>();
}
private COLOR(String value){
MapWrapper.myMap.put(value, this);
}
}
答案 2 :(得分:0)
您需要一个类似于以下内容的枚举声明方法:
private static enum COLOR {
BLACK(Color.BLACK, "Black"),
GREEN(Color.GREEN, "Green");
private Color color;
private String name;
COLOR(Color c, String n) {
this.name = n;
this.color = c;
}
public static COLOR convertToEnum(String value) {
for (COLOR v : values()) {
if (value.equalsIgnoreCase(v.name)) {
return v;
}
}
return null;
}
}