1. 程式人生 > 其它 >從一個類上獲取不到註解的原因

從一個類上獲取不到註解的原因

場景

定義一個註解
@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()