通过class类来实例化其他类的对象(使用有参构造函数)

时间:2021-11-08 09:20:37

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class InstanceDemo01 {
    public static void main(String[] args) {
        System.err.println(Person.class.getName());
        Class<?> c = null;
        try {
            c = Class.forName("Charp17Reflact.Person");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Person per = null;
       Constructor<?> cons[]=null;
        cons=c.getConstructors();
        try {
            per=(Person)cons[0].newInstance("VON fff",30);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        try {
//            per = (Person) c.newInstance();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//        per.setAge(82);
//        per.setName("von");
        System.out.println(per);
    }
}