2015-11-02 64 views

回答

1

似乎已經找到了答案:

((Class<? extends Enum>)clazz).getEnumConstants()[index]

雖然任何一找,你應該考慮以下@Daniel Pryden回答的最有可能的是,在大多數情況下,使用採用這種我能想到的是不好的做法。

1

依靠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; 
    } 
} 

然後,每當你想從MyThing得到thingId,只需調用getThingId()方法:

void doSomething(MyThing thing) { 
    System.out.printf("Got MyThing object %s with ID %d\n", 
    thing.name(), thing.getThingId()); 
} 

如果您希望能夠通過其thingId查找MyThing,您可以自己構建查找表並將其存儲在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對象可重複使用的機制。

+0

請注意,我不知道哪種類型是我的枚舉,並且它甚至可能不是我自己寫的枚舉,我只在運行時擁有類類型,我必須能夠處理它,所以您的答案是無辜的抱歉...無論如何。 –

+0

@OfekRon:這是一個不尋常的要求。你究竟想要做什麼?另外:請注意,這個答案不僅適用於您,也適用於正在搜索互聯網並找到您的問題的未來人士。即使這個答案對你來說「不相關」,也可能與其他人有關。 –

+0

不要以錯誤的方式,我沒有投票,因爲它是一個很好的答案,但它不是正確的答案,因此它不會被標記爲正確的。我正在寫一個使用反射的數據庫幫助程序,所以我不能假設所有我得到的枚舉都是由我寫的,或者正在實現我的接口。 –