本帖最后由 nestor 于 2014-4-17 14:54 编辑
代码:
- package javaGXJS.fanShe;
-
- import java.lang.reflect.Constructor;
-
- class Person{
- private String name;
- private int age;
-
- public Person() {
-
- }
- public Person(String name){
- this.name=name;
- }
- public Person(int age){
- this.age=age;
- }
- public Person(String name, int age) {
- this.age=age;
- this.name=name;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- @Override
- public String toString(){
- return "["+this.name+" "+this.age+"]";
- }
- }
-
- class reflect{
- public static void main(String[] args) throws Exception {
- Class demo=Class.forName("javaGXJS.fanShe.Person");
- Person per1=new Person();
- Person per2=null;
- Person per3=null;
- Person per4=null;
- //取得全部的构造函数
- Constructor[] cons=Class.forName("javaGXJS.fanShe.Person").getConstructors();
-
- per1=(Person)cons[0].newInstance(new Person());
- per2=(Person)cons[1].newInstance("Rollen");
- per3=(Person)cons[2].newInstance(20);
- per4=(Person)cons[3].newInstance("Rollen",20);
- System.out.println(cons[0]);
- System.out.println(cons[1]);
- System.out.println(cons[2]);
- System.out.println(cons[3]);
- }
- }
复制代码 报错代码:
per1=(Person)cons[0].newInstance(new Person());
per2=(Person)cons[1].newInstance("Rollen");
per3=(Person)cons[2].newInstance(20);
per4=(Person)cons[3].newInstance("Rollen",20);
错误信息:
- Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
- at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
- at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
- at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
- at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
- at javaGXJS.fanShe.reflect.main(dfgfdgfdg.java:45)
复制代码
|