反射方式获取成员方法并使用
Method对象
方法对象,属于java.base模块,java.lang.refect包
通过Class对象获取方法
getMethod(String name,Class<T>...parameterType) //返回一个Method对象,仅公共成员方法
getDeclaredMethod(String name,Class<T>...parameterType) //返回一个私有成员方法
getMethod() //返回所有的方法,不包含私有方法
Method的常用方法
String getName() //返回方法名
Object invoke(Object obj,Object... args) //在指定对象上调用此方法,参数为args
反射获取方法的例子
Student.java
package Demo01; import java.lang.reflect.Constructor; /** * @author :K; */ public class Student { public Student() { } public Student(String name){ System.out.println("输入的姓名为:"+name); } private Student(int age){ System.out.println("你的年龄为:"+age); } public void show(){ System.out.println("我是公共的无参方法"); } public void show2(int a){ System.out.println("我是公共的代参方法,你传入的参数为:"+a); } private int show3(int a,int b){ System.out.println("我是私有的代参方法"); return a+b; } }
Reflect_GetMethod.java
package Demo01; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Reflect_GetMethod { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class aClass = Class.forName("Demo01.Student"); Constructor constructor = aClass.getConstructor(); Student stu = (Student)constructor.newInstance(); Method show = aClass.getMethod("show"); show.invoke(stu); Method show2 = aClass.getMethod("show2", int.class); show2.invoke(stu, 20); Method show3 = aClass.getDeclaredMethod("show3",int.class,int.class); show3.setAccessible(true); //调用私有方法时,要设置它暴力反射 int invoke = (int)show3.invoke(stu, 20, 30); System.out.println(invoke); } }