Class.getConstructors()
method. Its method signature is this:
Constructor<?>[] getConstructors()The interesting thing here is that
Class.getConstructor(Class...)
returns a Constructor<T>
, with <T>
being maintained:
Constructor<T> getConstructor(Class<?>... parameterTypes)Why is there a difference, i.e. why doesn’t the first method return
Constructor<T>[]
?
Let’s consider the Javadoc:
Note that while this method returns an array of Constructor<T> objects (that is an array of constructors from this class), the return type of this method is Constructor<?>[] and not Constructor<T>[] as might be expected. This less informative return type is necessary since after being returned from this method, the array could be modified to hold Constructor objects for different classes, which would violate the type guarantees of Constructor<T>[].

Object[] objects = new String[1];
objects[0] = Integer.valueOf(1); // Ouch
Class.getConstructors()
method was Constructor[]
. A reasonable decision at the time. Of course, you could do the same mistake as above:
Object[] objects = String.class.getConstructors();
objects[0] = Integer.valueOf(1); // Ouch
Constructor[] constructors = String.class.getConstructors();
constructors[0] = Object.class.getConstructor();
// Muahahahahahahaha
List getConstructors()However, note that we didn’t have generics yet, so the array actually conveys more type information than the collection. Java 1.5: Generics In Java 5, the change from
Constructor[] getConstructors()to
Constructor<?>[] getConstructors()has been made for the reasons mentioned above. Now, the alternative API using a collection would definitely have been better:
List<Constructor<T>> getConstructors()But the ship has sailed.
Java, the ugly wart
Java is full of these little caveats. They’re all documented in the Javadocs, and often on Stack Overflow. Just yesterday, we’ve documented a new caveat related to completely new API inMap
and ConcurrentHashMap
.
“Stewardship: the Sobering Parts,” a very good talk about all those caveats and how hard it is to maintain them by Brian Goetz can be seen here:
The summary of the talk:
