dimanche 4 janvier 2015

surprising compilation error getting the array class of a class

Lately I've been doing a lot with reflection and implemented this little utility method. I was surprised to find that the first version does not compile, but the latter does.


Does not compile:



public static <T> Class<T[]> getArrayClassOfType(Class<T> componentType) {
return Array.newInstance(componentType, 0).getClass();
}


Compiles and works just fine:



public static <T> Class<T[]> getArrayClassOfType(Class<T> componentType) {
Class c = Array.newInstance(componentType, 0).getClass();
return c;
}


Two questions: what's wrong with it? is there a better way of doing this?


Here's the compilation error from the first:



TypeUtils.java:[12,60] incompatible types: java.lang.Class<capture#1 of ? extends java.lang.Object> cannot be converted to java.lang.Class<T[]>





Aucun commentaire:

Enregistrer un commentaire