java反射 反射构造函数 报 wrong number of arguments 错误

package com;

import java.lang.reflect.Constructor;

public class Person {
    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 void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString(){
            return "["+this.name+"  "+this.age+"]";
        }
        private String name;
        private int age;
    }
     
    class hello{
        public static void main(String[] args) throws Exception{
            Class<?> demo=null;
            
            try {
                demo=Class.forName("com.Person");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Person per1=null;
            Person per2=null;
            Person per3=null;
            Person per4=null;
            Constructor<?> cons[]=demo.getConstructors();
            per1=(Person)cons[0].newInstance();
            per2=(Person)cons[1].newInstance("as");
            per3=(Person)cons[2].newInstance(20);
            per4=(Person)cons[3].newInstance("as",20);
            System.out.println(per1);
            System.out.println(per2);
            System.out.println(per3);
            System.out.println(per4);
            
        }
        public static void asdsa(){
              Class<?> demo=null;
                try{
                    demo=Class.forName("com.Person");
                }catch (Exception e) {
                    e.printStackTrace();
                }
                Person per=null;
                try {
                    per=(Person)demo.newInstance();
                } catch (InstantiationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                per.setName("Rollen");
                per.setAge(20);
                System.out.println(per);
        }
}

出现这个错误:

 

解决方案:

 运行后:

 

posted @ 2018-07-09 20:21  韦邦杠  阅读(784)  评论(0编辑  收藏  举报