![](/img/trans.png)
[英]Get Enum Instance from Class<? extends Enum> using String value?
[英]Getting Enum from an integer having a Class<? extends Enum> object
似乎找到了答案:
((Class<? extends Enum>)clazz).getEnumConstants()[index]
盡管對於任何尋找它的人,您應該考慮遵循@Daniel Pryden 的回答,因為在我能想到的大多數用例中使用它很可能是不好的做法。
依賴 Java 枚舉常量的序數值是一種糟糕的做法——很容易意外地對它們重新排序,這會破壞您的代碼。 更好的解決方案是簡單地提供您可以使用的自己的整數:
public enum MyThing {
FOO(1),
BAR(2),
BAZ(3);
private final int thingId;
private MyThing(int thingId) {
this.thingId = thingId;
}
public int getThingId() {
return thingId;
}
}
然后,每當你想獲得thingId
從MyThing
,只需調用getThingId()
方法:
void doSomething(MyThing thing) {
System.out.printf("Got MyThing object %s with ID %d\n",
thing.name(), thing.getThingId());
}
如果您希望能夠查找一個MyThing
其thingId
,你可以自己建立一個查找表,並將其存儲在一個static final
字段:
private static final Map<Integer, MyThing> LOOKUP
= createLookupMap();
private static Map<Integer, MyThing> createLookupMap() {
Map<Integer, MyThing> lookupMap = new HashMap<>();
for (MyThing thing : MyThing.values()) {
lookupMap.put(thing.getThingId(), thing);
}
return Collections.unmodifiableMap(lookupMap);
}
public static MyThing getThingById(int thingId) {
MyThing result = LOOKUP.get(thingId);
if (result == null) {
throw new IllegalArgumentException(
"This is not a valid thingId: " + thingId);
}
return result;
}
如果你最終有很多枚舉類,並且你想對每個類做類似的事情,你可以為此定義一個接口:
public interface Identifiable {
int getId();
}
然后讓您的枚舉實現該接口:
public enum MyThing implements Identifiable {
...
@Override
public int getId() {
return thingId;
}
}
然后您可以構建一個可重用的機制,用於根據 ID 查找可Identifiable
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.