Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does casting a Type[] to a Class[] throw a ClassCastException?

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...

like image 216
Raibaz Avatar asked Nov 20 '25 21:11

Raibaz


1 Answers

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)?

like image 113
Joachim Sauer Avatar answered Nov 22 '25 11:11

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!