一、基础类
public class UserInfo { private long id; private String username; private String password; public UserInfo() { System.out.println("public UserInfo()"); } public UserInfo(long id) { super(); this.id = id; } public UserInfo(long id, String username) { super(); this.id = id; this.username = username; } public UserInfo(long id, String username, String password) { super(); this.id = id; this.username = username; this.password = password; System.out.println("public UserInfo(long id, String username, String password)"); System.out.println(id + " " + username + " " + password); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void test() { System.out.println("public void test1()"); } public void test(String address) { System.out.println("public void test2(String address) address=" + address); } public String test(int age) { System.out.println("public String test3(int age) age=" + age); return "我是返回值"; } }
二、反射创建对象
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class<UserInfo> userInfoClass = UserInfo.class; //1、使用Class对象调用无参构造方法 //UserInfo userInfo = userInfoClass.newInstance(); 已废弃,不推荐使用 UserInfo userInfo = userInfoClass.getDeclaredConstructor().newInstance(); userInfo.setId(666L); userInfo.setUsername("测试"); System.out.println(userInfo.getUsername()); //2、使用Class对象调用有参构造方法 UserInfo userInfo1 = userInfoClass.getDeclaredConstructor(long.class, String.class, String.class).newInstance(1L, "张三", "123456"); }
public UserInfo() 测试 public UserInfo(long id, String username, String password) 1 张三 123456