First, declaring the return type as Constructor<?>[]
does not imply creating an array of Constructor<?>
, does it? It's just saying "this method returns this type". Just saying that does not create an array, so no errors there.
But getConstructors
is going to create a Constructor<?>[]
somewhere in its implementation, right? How does that work?
Well, after tracing the source code of getConstructors
, I found this line where an array is created:
Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
This line (creating an empty array) is executed if the Class
is an interface. (If the Class
is not an interface, then a native
method gets called.) Why can a Constructor<?>[]
be created?
The Oracle documentation in this case is not 100% accurate (this is not to say you should not trust it anymore), because Constructor<?>
is a parameterised type, but new Constructor<?>[0]
is valid.
Let's have a look at what a more authoritative document - the Java Language Specification - says about creating arrays of generic types:
[...]
It is a compile-time error if the ClassOrInterfaceType does not denote
a reifiable type (§4.7). Otherwise, the ClassOrInterfaceType may name
any named reference type, even an abstract class type (§8.1.1.1) or an
interface type.
A reifiable type is defined as:
A type is reifiable if and only if one of the following holds:
The second bullet point applies to Constructor<?>
. This is why you could create a new Constructor<?>[10]
.