我正在尝试实施此方法:
public static <T> T[] convertListToArray(List<T> toConvert) { ... }
但是我无法将List<T>
对象转换为我需要实例化数组的Class<T>
对象。由于&#34; Type Erasure&#34;我不确定这是否可行,但我想我会尝试。这是我在被困之前走了多远:
public static <T> T[] convertListToArray(List<T> toConvert) throws Exception {
Class<?> curClass = Class.forName("thispackage.ListUtils");
Method method = curClass.getDeclaredMethod("convertListToArray", List.class);
Type[] typeArray = method.getGenericParameterTypes();
ParameterizedType listType = (ParameterizedType)typeArray[0];
Type[] genericTypes = listType.getActualTypeArguments();
TypeVariable genericType = (TypeVariable)genericTypes[0];
//Got stuck here, can a "TypeVariable" be converted to a "Class<?>"?
String genericName = genericType.getTypeName();
System.out.println(genericName); //Prints "T"
//this of course doesn't work, throws ClassNotFoundException at runtime
Class<?> arrayClass = Class.forName(genericName);
int size = toConvert.size();
T[] retArray = (T[])Array.newInstance(arrayClass, size);
return toConvert.toArray(retArray);
}
那么,是否可以将TypeVariable
转换为Class<?>
?
答案 0 :(得分:-1)
关键是要弄清楚T
的类型是什么,尽管真正使用了这种方法,但这只会起作用。
@SuppressWarnings("unchecked")
public static <T> T[] convertListToArray(List<T> toConvert) throws Exception {
if (!toConvert.isEmpty()) {
Class<?> aClass = toConvert.get(0).getClass();
T[] t = (T[]) Array.newInstance(aClass, toConvert.size());
return toConvert.toArray(t);
}
return (T[]) toConvert.toArray();
}