ajb ajb - 2 years ago 118
Java Question

getDeclaredConstructor on an interface?

The javadoc for

(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
and got
. Is there a case where
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()) {
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download