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