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/