我试图通过这个例子来理解这种差异:
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
try {
// returns the Constructor object of the public constructor
//Class cls[] = new Class[] { String.class };
Constructor c = String.class.getConstructor();
System.out.println(c);
}
catch(Exception e) {
System.out.println(e);
}
}
}
我得到这个结果:
public java.lang.String()
在这个例子中,如果我替换:
Constructor c = String.class.getConstructor();
通过:
Constructor c = String.class.getConstructor((Class<?>[]) null);
我得到了相同的结果...
为什么以及什么是微妙之处?
提前致谢。
最佳答案
他们做的事情完全一样。
当您调用 String.class.getConstructor()
时,你实际上有一个空数组 Class<?>
作为论据。这等于使用 (Class<?>[]) null
调用它,这可以通过检查它将类型参数与构造函数中的参数进行比较的方式看出:
private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
if (a1 == null) {
return a2 == null || a2.length == 0;
}
if (a2 == null) {
return a1.length == 0;
}
if (a1.length != a2.length) {
return false;
}
for (int i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}
如您所见,空数组和 null 被视为相等。您也可以使用 new Class<?>[0]
来调用它作为参数。
关于java - "getConstructor()"和 "getConstructor((Class<?>[]) null)"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31404035/