I'm currently studying Java Collections Framework, and one of the fascinating questions that I keep asking myself is "How do all these collections implement the generic version of Collection#toArray method". From what I've read in other SO questions, it most probably uses Array#newInstance. Just for the reference, that's how Array#newInstance is declared:
public static Object newInstance(Class<?> componentType,
int... dimensions)
throws IllegalArgumentException,
NegativeArraySizeException
Now, my question is: how to make the information supplied to that method enough to produce an array object of a specified type?
The multi-dimensionality aspect isn't that difficult, as one could always construct an N-dim array as a single-dim array of (N-1)-dim arrays.
What really bugs me is how to create an object of type T[] from a Class<T> object passed via the Class<?> reference.
newInstancedelegates to aprivateandnativemethod which actually returns the new array. The actual creation is done dynamically by the JVM.Serializable, but ignore that).