Joh*_*ley 17 java generics reflection polymorphism enums
我有一些辅助方法可以将枚举值转换为适合HTML <select>
元素显示的字符串列表.我想知道是否可以将这些重构为单一的多态方法.
这是我现有方法之一的示例:
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
我仍然是Java泛型的新手,所以我不确定如何将泛型枚举传递给该方法并在for循环中使用它.
请注意,我知道有问题的枚举都将具有该getDisplayValue
方法,但遗憾的是它们不共享定义它的常见类型(我不能引入一个),所以我想这将是必须反复访问的.. .?
在此先感谢您的帮助.
dfa*_*dfa 17
使用Class#getEnumConstants()很简单:
static <T extends Enum<T>> List<String> toStringList(Class<T> clz) {
try {
List<String> res = new LinkedList<String>();
Method getDisplayValue = clz.getMethod("getDisplayValue");
for (Object e : clz.getEnumConstants()) {
res.add((String) getDisplayValue.invoke(e));
}
return res;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
这不是完全类型安全的,因为你可以拥有一个没有getDisplayValue
方法的枚举.
Joh*_*eek 10
您可以将此方法粘贴到某个实用程序类中:
public static <T extends Enum<T>> List<String> getDisplayValues(Class<T> enumClass) {
try {
T[] items = enumClass.getEnumConstants();
Method accessor = enumClass.getMethod("getDisplayValue");
ArrayList<String> names = new ArrayList<String>(items.length);
for (T item : items)
names.add(accessor.invoke(item).toString()));
return names;
} catch (NoSuchMethodException ex) {
// Didn't actually implement getDisplayValue().
} catch (InvocationTargetException ex) {
// getDisplayValue() threw an exception.
}
}
Run Code Online (Sandbox Code Playgroud)
来源:检查枚举