1、方法

获取成员方法们:

  1. Method[] getMethods()
  2. Method getMethod(String name, 类<?>... parameterTypes)
  3. Method[] getDeclaredMethods()
  4. Method getDeclaredMethod(String name, 类<?>... parameterTypes)

2、使用

Method:方法对象

  • 执行方法: (重要)
    • Object invoke(Object obj, Object… args)
  • 获取方法名称:
    • String getName:获取方法名

3、代码

  1. public static void main(String[] args) throws Exception {
  2. //0.获取Person的Class对象
  3. Class personClass = Person.class;
  4. /*
  5. 3. 获取成员方法们:
  6. * Method[] getMethods()
  7. * Method getMethod(String name, 类<?>... parameterTypes)
  8. * Method[] getDeclaredMethods()
  9. * Method getDeclaredMethod(String name, 类<?>... parameterTypes)
  10. */
  11. //获取指定名称的方法
  12. Method eat_method = personClass.getMethod("eat");
  13. Person p = new Person();
  14. //执行方法
  15. eat_method.invoke(p);
  16. Method eat_method2 = personClass.getMethod("eat", String.class);
  17. //执行方法
  18. eat_method2.invoke(p,"饭");
  19. System.out.println("-----------------");
  20. //获取所有public修饰的方法
  21. Method[] methods = personClass.getMethods();
  22. for (Method method : methods) {
  23. System.out.println(method);
  24. String name = method.getName();
  25. System.out.println(name);
  26. //method.setAccessible(true);
  27. }
  28. //获取类名
  29. String className = personClass.getName();
  30. System.out.println(className);//cn.itcast.domain.Person
  31. }