java - 接口(interface)上的getDeclaredConstructor?

标签 java reflection

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

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

既然不能为接口(interface)声明构造函数,那么返回接口(interface)的“指定构造函数”意味着什么?

我在 Runnable.class 上试了一下,得到了 NoSuchMethodException。是否存在 getDeclaredConstructor 可以在接口(interface)上工作的情况?或者javadoc中的这种语言只是一个错误?或者它的意思不是我的解释?

最佳答案

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;
}

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

因此,对于接口(interface),构造函数列表始终为空,并且始终会抛出 NoSuchMethodException

关于java - 接口(interface)上的getDeclaredConstructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36564041/

相关文章:

java - 如何实现将返回枚举的具体类型的方法签名?

java.net.SocketException : Socket is closed while socket is still open

java - 一次 JSF/Seam 更改的多个 AJAX 请求

java - 有没有一种优雅的方式在 Springs @Query 注释中使用枚举?

C# 反射不适用于 Point 类?

java - 是否有 Class.isAssignableFrom 与 Type 对象一起使用的替代方法?

java - 下载文件需要很长时间

c# - 是否可以将反射访问器缓存到支持字段以进行优化?

php - 是否应该使用反射或实例化来判断一个类是否存在并实现了一个接口(interface)?

java - JVM 中可以驻留多少个类文字实例?