下面代码中的Class[] null
和Object[] null
是什么意思?
public Object selfFactory() {
Class cl = this.getClass();
Constructor cons;
cons = cl.getConstructor((Class[]) null);
return cons.newInstance((Object[]) null);
}
最佳答案
cl.getConstructor((Class[]) null);
将参数的值和类型作为类型参数 <T>
,因此如果我们提供 null
则需要进行转换Class[]
而不是null
Object
用于 .getConstructor()
的方法调用.
同样,cons.newInstance((Object[]) null);
创建 cl
的新实例通过调用构造函数 cons
这需要 Object[]
,给出为 null
在这种情况下。如果没有类型转换,则为 null Object
将会通过。
这在方法或构造函数重载时很有用。调用null
如果没有强制转换,则类型为 Object
并且常常含糊不清:
{
eat(null); // ???
}
void eat(int[] arr);
void eat(Class arr);
通过强制转换,可以调用正确的构造函数或方法。
{
eat((Class) null);
}
也如 polygenelubricants 所记录在 How to work with varargs and reflection ,
[...]
invoke(Object obj, Object... args)
makes it tricky if you need to pass an array of reference type as an only argument, because it is cast-able toObject[]
, even though it should be wrapped inside anew Object[1]
instead.You can do:
m.invoke(this, new Object[] {a}); // Bohzo's solution
This bypasses the vararg mechanism. More succinctly you can also do:
m.invoke(this, (Object) a);
The cast to
Object
makes the vararg mechanism do the work of creating the array for you.The trick is also needed when passing a
null
as an argument to varargs, and has nothing to do with reflection.public void foo(String... ss) { System.out.println(ss[0]); } foo(null); // causes NullPointerException foo((String) null); // prints "null"
关于java - java中使用反射动态创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26338018/