反射newinstance构造函数java错误的参数个数

时间:2015-05-12 10:56:59

标签: java reflection constructor

我正在学习Java中的Reflection,并尝试以构造函数为例。但是有一个问题:"参数数量错误"。 搜索谷歌和stackoverflow,我找不到与我目前面临的相同的问题。 谁能帮助我理解这个问题,非常感谢你。 这是我的代码:

    public static void main(String[] args) {
    PrintClass f = new PrintClass();
    Class cl = f.getClass();
    Constructor<?> constructor[] = cl.getDeclaredConstructors(); // cl.getDeclaredConstructors() also won't work...

    f.field1 = 3;
    PrintClass p1 = null;
    PrintClass p2 = null;

    try {
        p1 = (PrintClass) constructor[0].newInstance(); // constructor[0].newInstance((Object[])args) also won't work...
        p2 = (PrintClass) constructor[1].newInstance("this is not PrintClass-------");

        p1.print();
        p2.print();

    } catch (InstantiationException | IllegalAccessException
            | IllegalArgumentException | InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }
}

class PrintClass {
String s = "this is PrintClass...";
int field1;

public PrintClass(String s) {
    this.s = s;
}

public PrintClass() {
}

public void print() {
    System.out.println(s);
}

}

这是错误

java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at reflection.MainClass.main(MainClass.java:18)

再次,非常感谢你帮助我理解这个问题。 :)

1 个答案:

答案 0 :(得分:2)

你在没有参数的情况下调用两个构造函数中的第一个。但是,如何确定数组中的第一个构造函数是没有参数的构造函数,而不是期望字符串的构造函数?

你不能,因为the javadoc说:

  

返回的数组中的元素没有排序,也没有任何特定的顺序。

如果要引用类的无参数构造函数,则应调用

cl.getDeclaredConstructor();

如果你想引用以STring为参数的构造函数,你应该调用

cl.getDeclaredConstructor(String.class);
相关问题