Reputation: 1437
Imagine this piece of code:
public static <T> T[] superClassArray(Class<? extends T[]> subClass) {
T[] superArray = (T[]) Array.newInstance(subClass.getComponentType().getSuperclass(), 0);
return superArray;
}
The return type T[]
of this method would be of whatever type was given as argument subClass
, even thought subClass
is not garanted to actually represent T[]
but just a subclass (? extends T
). So the actual return type should be Object
since T[]
is not declared more explicitly than being any superclass of subclass
.
However,
Integer[] objA = superClassArray(Integer[].class);
compiles because it is erroneously expected to return a Integer[]
object but obviously throws a ClassCastException
because a Number[]
object is actually returned.
So is there a justification for poor handling of generic types only declared through rather vague wildcards, or am I mistaken at any point of my consideration?
Upvotes: 2
Views: 103
Reputation: 2272
As far as I understand, you are not very consistent in what you are trying to do. With your method you are creating an array of SUPERTYPE of your class, which actually succeds.
But then you are trying to assign it to a reference to a SUBTYPE which is illegal. If you are actually sure that this array cannot contain values of any other type than Integer you can explicitly cast it:
Integer[] objA = (Integer[]) superClassArray(Integer[].class);
BUT I don't see any value at all in a code like that and in the real world if you have a task that you are trying to solve with something like this, you sould really think about it a few more times and come up with a better solution. :)
Upvotes: 1
Reputation: 2265
You are not supposed to do any manual casting. Generics has to handle that during compile time. If you get compile time error, You better fix this instead of doing unsafe casting in your below code snippet.
T[] superArray = (T[])Array.newInstance(subClass.getComponentType().getSuperclass(), 0);
Upvotes: 0