我有一些幫助器方法可將枚舉值轉換爲適合由HTML <select>
元素顯示的字符串列表。我想知道是否有可能將這些重構爲單一的多態方法。將Java枚舉值多態轉換爲字符串列表
這是我現有的方法中的一個例子:
/**
* Gets the list of available colours.
*
* @return the list of available colours
*/
public static List<String> getColours() {
List<String> colours = new ArrayList<String>();
for (Colour colour : Colour.values()) {
colours.add(colour.getDisplayValue());
}
return colours;
}
我還是很新的Java泛型,所以我不知道如何將通用枚舉傳遞給方法,並有也在for循環中使用。
請注意,我知道所有有問題的枚舉都會有這個getDisplayValue
方法,但不幸的是它們沒有共享一個定義它的通用類型(我不能引入它),所以我想這將不得不反射式地訪問...?
在此先感謝您的幫助。
不使用getDisplayValue方法。 – 2009-08-11 16:08:04
修改,請查看異常處理 – dfa 2009-08-11 16:14:55
很好地工作,謝謝! – 2009-08-11 16:16:55