views:

79

answers:

3

Today i was writing some heavy reflection-using code, and i came across this behavior i can't explain: why does

Type[] types = ((ParameterizedType)m.getGenericReturnType()).getActualTypeArguments();
Class[] c = (Class[])types;

Throw a ClassCastException, when iterating over that same array and casting every single element, i.e.

for(Type t : types) {
    Class c = (Class)t;
}

succeeds?

I mean, if the casting of a single element to another class is possible, why isn't the casting between arrays of the same types possible as well?

There probably is a reason, but i can't seem to find one...

+5  A: 

You can't cast a Type[] to a Class[] because a Type[] is not a Class[]. It may sound trivial, but that's all there is to it.

If you could cast a Type[] to a Class[], what would you expect to happen when one of its elements was a Type that isn't a Class (a ParameterizedType for example)?

Joachim Sauer
i understand, but then shouldn't the ClassCastException be thrown only if one of the elements isn't a Class instead of being thrown everytime?
Raibaz
No, because the actual run-time type is not a `Class[]`, just as an instance of `Object` (created with `new Object()`) cannot magically be turned into a `String`. See my answer below
thecoop
+1  A: 

Bear in mind that to cast to a Class[], the object has to actually be a Class[], not a Type[]. As an example, this will fail:

Object[] objArr = new Object[10];
Integer[] intArr = (Integer[])objArr;  // fail.

but this will work:

Object[] objArr = new Integer[10];
Integer[] intArr = (Integer[])objArr;
thecoop
A: 

You can't cast whole array, because there is no guarantee that all the elements in the array are of type Class. What if one of them was some other implementation of Type?

amorfis