一、基础类
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, NoSuchFieldException { Class<UserInfo> userInfoClass = UserInfo.class; //1、使用Class对象调用无参构造方法 //UserInfo userInfo = userInfoClass.newInstance(); 已废弃,不推荐使用 UserInfo userInfo = userInfoClass.getDeclaredConstructor().newInstance(); //定义方法名方法名 String methodName = "test"; //1、获取无参无返回值方法对象 Method test1 = userInfoClass.getDeclaredMethod(methodName); //执行方法 test1.invoke(userInfo); // 2、获取有参无返回值方法 Method test2 = userInfoClass.getDeclaredMethod(methodName, String.class); test2.invoke(userInfo, "地址参数"); // 3、获取有参有返回值方法 Method test3 = userInfoClass.getDeclaredMethod(methodName, int.class); String result = (String) test3.invoke(userInfo, 12); System.out.println(result); }
public UserInfo() public void test1() public void test2(String address) address=地址参数 public String test3(int age) age=12 我是返回值