天天看点

如何用反射,调用带参数的构造方法创建对象

如何用反射,调用带参数的构造方法创建对象

1.创建一个实体对象,以及待参数的构造方法,getset自己补全

public class User {
    private String name;
    private String age;

    public User(String name) {
        this.name = name;
    }
}    
           

2.创建反射对象,调用构造方法创建对象

public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<User> userClass = User.class;
        Constructor<User> constructor = userClass.getConstructor(String.class);
        User user = constructor.newInstance("张三");
        System.out.println(user);
    }