0

我有一个这样定义的枚举:

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")
4

3 回答 3

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();
    }
于 2013-04-18T18:53:36.160 回答
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);
      }
 }
于 2013-04-18T18:55:06.427 回答
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;
    }
}
于 2013-04-18T19:10:53.377 回答