Demo02.java 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. package J20250806.annotation;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. /**
  5. * @author WanJl
  6. * @version 1.0
  7. * @title Demo02
  8. * @description
  9. * @create 2025/8/6
  10. */
  11. public class Demo02 {
  12. public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
  13. //1、通过反射获取UserTest类的字节码对象
  14. Class<?> clazz = Class.forName("J20250806.annotation.UserTest");
  15. //2、通过反射创建对象
  16. UserTest userTest =(UserTest) clazz.newInstance();
  17. //3、通过反射获取这个类里面的所有方法的对象
  18. Method[] methods = clazz.getDeclaredMethods();
  19. //4、遍历这个数组
  20. for (Method method:methods){
  21. //我们可以拿到UserTest对象的每一个方法对象
  22. //可以同一个方法来判断这个方法对象有没有标注注解
  23. if (method.isAnnotationPresent(MyTest.class)){
  24. //如果这个方法对象标注了MyTest注解,那么就执行这个方法
  25. method.invoke(userTest);
  26. }
  27. }
  28. }
  29. }