Demo07_MethodTest.java 1.0 KB

123456789101112131415161718192021222324252627282930
  1. package J20250806.reflection;
  2. import java.lang.reflect.Method;
  3. import java.util.Arrays;
  4. /**
  5. * @author WanJl
  6. * @version 1.0
  7. * @title Demo07_MethodTest
  8. * @description Class获取方法相关操作
  9. * @create 2025/8/6
  10. */
  11. public class Demo07_MethodTest {
  12. public static void main(String[] args) throws NoSuchMethodException {
  13. Class<Person> personClass = Person.class;
  14. //获取所有公共方法--包含从父类继承的方法
  15. Method[] personClassMethods = personClass.getMethods();
  16. System.out.println(Arrays.toString(personClassMethods));
  17. //获取所有方法
  18. Method[] personClassDeclaredMethods = personClass.getDeclaredMethods();
  19. System.out.println(Arrays.toString(personClassDeclaredMethods));
  20. //获取单个公共方法
  21. Method setName = personClass.getMethod("setName", String.class);
  22. System.out.println(setName);
  23. //获取单个方法
  24. Method showName = personClass.getDeclaredMethod("showName", String.class);
  25. System.out.println(showName);
  26. }
  27. }