ajb ajb - 1 year ago 66
Java Question

getDeclaredConstructor on an interface?

The javadoc for

Class::getDeclaredConstructor
(http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...-) says:


Returns a Constructor object that reflects the specified constructor
of the class or interface represented by this Class object. [emphasis mine]


Since you can't declare a constructor for an interface, what could it mean to return a "specified constructor" of an interface?

I tried it on
Runnable.class
and got
NoSuchMethodException
. Is there a case where
getDeclaredConstructor
will work on an interface? Or is this language in the javadoc just an error? Or does it mean something other than how I'm interpreting it?

Answer Source

A call to Class.getConstructor will result in a call to Class.privateGetDeclaredConstructors to retrieve all declared constructors. The matching constructor is selected from that list:

private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
    ...
    // No cached value available; request value from VM
    if (isInterface()) {
        @SuppressWarnings("unchecked")
        Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
        res = temporaryRes;
    } else {
        res = getDeclaredConstructors0(publicOnly);
    }
    ...
    return res;
}

(I removed part of the code which deals with cached constructors).

So for interfaces the constructor list is always empty and a NoSuchMethodException will always be thrown.