mardi 31 mars 2015

In Java, can a TypeVariable be converted to a Class object?

I'm trying to implement this method:



public static <T> T[] convertListToArray(List<T> toConvert) { ... }


But I have been unable to convert the List<T> object into a Class<T> object which I need to instantiate the array. I'm not sure if this is even possible due to "Type Erasure", but thought I would try. Here is how far I got before getting stuck:



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);
}


So, is it possible to convert a TypeVariable into a Class<?>?






Aucun commentaire:

Enregistrer un commentaire