java 反射 获取方法
一、获取
1、语法
// 1.获取所有public方法对象,包括父类 class对象..getMethods(); // 2.获取 所有方法对象 包括private 修饰,但不包括父类对象 class对象.getDeclaredMethods(); // 3. 获取指定的方法对象(只含public),无参数,直接指定方法名 class对象.getMethod("方法名", ..参数,class); // 4.获取指定的方法对象(包含private),有参,无参 class对象.getDeclaredMethod("方法名", ...参数.class);
2、案例
@Test public void getMethod() throws Exception{ Class<Person> personClass = Person.class; // 所有方法,只含public Method[] methods = personClass.getMethods(); for (Method method : methods) { System.out.println(method); } // 所有方法,包含private System.out.println("================================="); Method[] methods1 = personClass.getDeclaredMethods(); for (Method method : methods1) { System.out.println(method); } System.out.println("---------------------------------"); // 指定方法 无参数,只含public Method getName = personClass.getMethod("getName"); System.out.println(getName); // 指定方法,有参数 System.out.println("================================="); Method setName = personClass.getMethod("setName", String.class); System.out.println(setName); // 指定方法,无参/有参, 包含private Method eat = personClass.getDeclaredMethod("eat"); System.out.println(eat); }
二、使用
1、语法
// 1.有参 方法对象.invoke(对象, ...实参); // 2,无参 方法对象.invoke(对象);
注意:private修饰的方法
方法对象.setAccessible(true);
2、案例
@Test public void methodUsed() throws Exception { Class<Person> personClass = Person.class; // 获取构造对象 Constructor<Person> personConstructor = personClass.getConstructor(String.class, Integer.class); // 创建对象 Person person = personConstructor.newInstance("小红", 19); // 有参 Method setName = personClass.getMethod("setName", String.class); // 设置 setName.invoke(person, "小姐"); System.out.println(person); // 无参获取 Method getAge = personClass.getMethod("getAge"); Object age = getAge.invoke(person); System.out.println("age = " + age); // 私有方法 Method eat = personClass.getDeclaredMethod("eat"); eat.setAccessible(true); // 调用方法 eat.invoke(person); }