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

标签 java class reflection constructor

下面代码中的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/

相关文章:

c++ - 代码块无法识别它编写的类的标题?

c# - 如何从此类中的委托(delegate)访问类的实例方法

java - 如何将 "dynamically"对象类型的实例转换为其特定数据类型?

java - Android根据标签获取 View ID

java - 将对象添加到列表中的 Lambda 表达式

java - Android Studio - 在一个异步任务中从 2 个 url 下载 JSON 数据

java - Scala TypeTag 到 java.lang.reflect.Type

java - 如何解决 MathCalculationException 异常问题?

c++ - 打印实现在推回后立即失败( vector )

c# - 使用参数安全调用多次调用泛型方法(运行时返回类型)的最佳方法