0
点赞
收藏
分享

微信扫一扫

javase:反射注解

书坊尚 2022-01-07 阅读 91
java
import java.lang.reflect.Method;

public class ReflectAnnotation {
    public static void main(String[] args) throws Exception {
        // 获取这个类
        Class c = Class.forName("com.MyAnnotationTest");

        // 判断类上面是否有@MyAnnotation。
        System.out.println(c.isAnnotationPresent(MyAnnotation.class));

        if (c.isAnnotationPresent(MyAnnotation.class)) {
            // 获取上面的注解。返回的是Annotation类型,需要向下转型。
            MyAnnotation myAnnotation = (MyAnnotation) c.getAnnotation(MyAnnotation.class);
            System.out.println("类上面的注解对象是:" + myAnnotation);

            // 获取注解对象的属性。
            String value = myAnnotation.value();
            System.out.println(value);
        }

        // 获得doSome方法。
        Method d =c.getDeclaredMethod("doSome");

        if (d.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation myAnnotation1 = d.getAnnotation(MyAnnotation.class);
            System.out.println("方法上面的注解对象是:" + myAnnotation1);
        }
    }
}
举报

相关推荐

JavaSE:注解和反射

【JavaSE总结】注解和反射

【javaSE】反射

javase:反射对象

Javase 反射机制

JavaSE——注解

javase:注解

JavaSE之注解

0 条评论