The bottom line is that the class representing the array must know the type of component. Therefore, the method of the Class object:
public Class<?> getComponentType() Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.
So when you try:
A[] a = new A[0];
At compile time, it is obvious that we do not know the type, since this is a general parameter. At run time, we do not know the type due to the erasure of the type. Thus, creating an instance of the array is not possible.
Recall the above statement as equivalent:
A[] a = (A[])Array.newInstance(???, 0);
And due to type erasure, we cannot get class A at runtime.
It was asked, why not compile the compiler for Object [] or Number [] or something like that?
This is because, depending on the type of component, another class will be returned. So:
new Object[0].getClass() new Integer[0].getClass()
are not the same class. In particular, the getComponentType () method in the class returns different values.
So, if you reduce it to Object [] instead of A [], you will not actually get something like A [], you will return Object []. The [] object cannot be compiled by Integer [] and will throw a ClassCastException.
Matt
source share