场景
定义一个注解
@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()
@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()