如何用反射,調用帶參數的構造方法建立對象
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);
}