Reputation: 1173
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.
Upvotes: 2
Views: 974
Reputation: 122489
If you think about it, it makes sense to have such a functionality in the Reflection API. When you do new SomeType[N]
, the compiler basically compiles into the byte code something that says, create a new array, with component type SomeType
, and length N
.
So the JVM must have some mechanism at runtime already to evaluate such instructions, that given a given component type, and length, allocates a new array. The only problem with new SomeType[N]
is that the component type is hard-coded at compile-time. But it would be no more difficult for the JVM if the type were given at runtime, since the JVM has a runtime mechanism that takes the type. Since there is no native syntax that allows you to create an array with a dynamic type, the Reflection API provides a method to do it.
Upvotes: 1
Reputation: 183
It's logically correct to have this ability and jdk offer this by Array.newInstance method. But the implementation is inside the jvm, so you cannot know how they exactly implement this in non-opensource jvm. I suggest you to examine the openJVM source code because they offer the similar ability.
Upvotes: 0