Why casting a class [] to a class [] throws a ClassCastException?

Today I wrote some heavy reflexive code, and I came across this behavior, I can not explain: why

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

Throw a ClassCastException when repeating the same array and casting each individual element, i.e.

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

succeeds?

I mean, if casting one element into another class is possible, then why can't there be a listing between arrays of the same types?

There is probably a reason, but I cannot find it ...

+3
source share
3 answers

You cannot distinguish Type[]from Class[], because it is Type[]not Class[]. It may seem trivial, but all that he needs.

Type[] Class[], , Type, Class (a ParameterizedType )?

+5

, Class[] Class[], Type[]. , :

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

:

Object[] objArr = new Integer[10];
Integer[] intArr = (Integer[])objArr;
+1

You cannot use a whole array because there is no guarantee that all elements of the array are of type Class. What if one of them was another implementation Type?

0
source

Source: https://habr.com/ru/post/1763965/


All Articles