通过反射获取成员方法并使用

it2023-11-01  71

Student.java

package student.demo; public class Student { public void show1(){ System.out.println("公共的空参方法"); } public void show2(int a){ System.out.println("公共的带参数的方法"); } private void show3(int a, int b){ System.out.println("私有的带参方法"); System.out.println(a+b); } }

Test.java

package student.demo; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class Test { public static void main(String[] args) throws Exception{ Class clazz = Class.forName("student.demo.Student"); Constructor con = clazz.getConstructor();//获取空参构造 Student stu = (Student) con.newInstance();//实例化 Method method = clazz.getMethod("show1");//获取公共的空参方法show1 method.invoke(stu);//调用方法 传入实例化的对象 Method method2 = clazz.getMethod("show2", int.class); method2.invoke(stu, 10);//调用方法 传入实例化的对象 ,如果有参数就传参数 Method method1 = clazz.getDeclaredMethod("show3", int.class, int.class);//获取所有方法 method1.setAccessible(true);//暴力反射,设置了之后可以访问私有方法 method1.invoke(stu,10, 20); } }

 

最新回复(0)