从一个类上获取不到注解的原因

场景

定义一个注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

一个父类
@MyAnnotation
public class OneClass {
}

一个子类
public class TwoClass extends OneClass {
}
public class Main {
    public static void main(String[] args) {
        System.out.println(OneClass.class.getAnnotation(MyAnnotation.class));
        System.out.println(TwoClass.class.getAnnotation(MyAnnotation.class));
    }
}
@cn.eagle.li.java.reflect.annnotation.MyAnnotation()
null

可以看出 从子类身上是获取不到 注解的

解决方案:

  • 使用 Spring中的工具类 AnnotationUtils
public class Main {
    public static void main(String[] args) {
        System.out.println(OneClass.class.getAnnotation(MyAnnotation.class));
        System.out.println(TwoClass.class.getAnnotation(MyAnnotation.class));
        System.out.println(AnnotationUtils.findAnnotation(TwoClass.class, MyAnnotation.class));
    }
}
@cn.eagle.li.java.reflect.annnotation.MyAnnotation()
null
@cn.eagle.li.java.reflect.annnotation.MyAnnotation()
  • 在注解上加上元注解 @Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
}
public class Main {
    public static void main(String[] args) {
        System.out.println(OneClass.class.getAnnotation(MyAnnotation.class));
        System.out.println(TwoClass.class.getAnnotation(MyAnnotation.class));
        System.out.println(AnnotationUtils.findAnnotation(TwoClass.class, MyAnnotation.class));
    }
}
@cn.eagle.li.java.reflect.annnotation.MyAnnotation()
@cn.eagle.li.java.reflect.annnotation.MyAnnotation()
@cn.eagle.li.java.reflect.annnotation.MyAnnotation()
posted @ 2022-03-25 13:12  eaglelihh  阅读(540)  评论(0编辑  收藏  举报