2013-04-18 115 views
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") 

回答

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(); 
    } 
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); 
     } 
} 
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; 
    } 
}