下面是我用的模式:
enum X {
A("a"), B("b"), ...;
private final static Map<String,X> MAP = new HashMap<String,X>();
static {
for(X elem: X.values()) {
if(null != MAP.put(elem.getValue(), elem)) {
throw new IllegalArgumentException("Duplicate value " + elem.getValue());
}
}
}
private final String value;
private X(String value) { this.value = value; }
public String getValue() { return value; }
// You may want to throw an error here if the map doesn't contain the key
public static X byValue(String value) { return MAP.get(value); }
}
這看起來有點奇怪訪問enum
類型的實例在static
塊enum
聲明內,但此代碼的工作。
在你的情況下,可能會看起來像這樣:
String fieldName = Code.valueOf(Code.class).getValue();
見http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf%28java.lang.Class,%20java.lang.String %29 – 2012-10-08 12:44:33
我想我不清楚。我有興趣引用這個枚舉。 – Madrugada