gpt4 book ai didi

java - java中使用反射动态创建对象

转载 作者:行者123 更新时间:2023-12-01 17:04:04 25 4
gpt4 key购买 nike

下面代码中的Class[] nullObject[] 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 to Object[], even though it should be wrapped inside a new 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com