我有一个这样定义的枚举:
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;
}
我试图找到一种方法来根据字符串(这是第二个附加参数)获取枚举常量。因此,对于一个完全假设的示例,我会做类似的事情
COLOR.getEnumFromString("Green")
最佳答案
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();
}
关于java - 根据附加值获取枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16090870/