Class类

成员方法

  1. public Method getMethodString name,Class... params);<br /> 返回一个Method对象,仅公共成员方法<br /> public Method getDeclaredMethodString ,class... params);<br /> 返回一个Method对象,可获取私有成员方法<br /> public Method[] getMethods();<br /> 返回此类所有(不含私有)方法数组

Method类

方法类,用来表示所有的成员方法(对象)的

概述

属于java.base模块下的java.lang.reflect包下的类

成员方法

  1. public String getName(); 获取成员方法名<br /> public Object invokeObject obj,Object... params); 调用指定方法,obj表示该类的对象,params表示调用该方法所需的参数<br /> public void setAccessible(boolean flag); 是否开启暴力反射(true:开启)

案例

  1. public class ReflectDemo2 {
  2. public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
  3. //需求:通过反射获取Student类中的成员方法并调用
  4. //1.获取Student类的字节码文件对象
  5. Class clazz =Class.forName("Note.Student");
  6. //2.获取该类的构造器对象,然后创建Student类的对象
  7. Constructor con = clazz.getConstructor();
  8. Student stu = (Student) con.newInstance();
  9. // System.out.println(stu);
  10. //3.获取该类的成员方法对象,然后调用此方法
  11. //3.1调用公共的空参方法
  12. Method method1 = clazz.getMethod("show1");
  13. System.out.println(method1);
  14. //打印方法名
  15. System.out.println(method1.getName());
  16. //调用此方法
  17. method1.invoke(stu);
  18. //3.2调用一个公共的带参方法
  19. Method method2 = clazz.getMethod("show2", int.class);
  20. method2.invoke(stu,100);
  21. //3.3调用私有的带参方法
  22. Method method3= clazz.getDeclaredMethod("show3", int.class, int.class);
  23. method3.setAccessible(true);
  24. int num = (int) method3.invoke(stu, 10, 20);
  25. System.out.println("你录入的两个值的和为:"+num);
  26. //3.4获取Student类中的所有的成员方法
  27. Method methods[] =clazz.getMethods();
  28. for (Method method : methods) {
  29. System.out.println(method);
  30. }
  31. }
  32. }