接口上的getDeclaredConstructor?

ajb*_*ajb 25 java reflection

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

返回一个Constructor对象,该对象反映此Class对象所表示的类或接口的指定构造函数.[强调我的]

既然你不能为接口声明构造函数,那么返回接口的"指定构造函数"意味着什么呢?

我试过了Runnable.class,得到了NoSuchMethodException.是否有getDeclaredConstructor可以在界面上工作的情况?或者javadoc中的这种语言只是一个错误?或者它是否意味着除了我如何解释它之外的东西?

wer*_*ero 9

调用Class.getConstructor将导致调用Class.privateGetDeclaredConstructors以检索所有已声明的构造函数.从该列表中选择匹配构造函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

(我删除了部分处理缓存构造函数的代码).

因此,对于接口,构造函数列表始终为空,并且NoSuchMethodException将始终抛出a.