文章目录
本章单独针对MergedAnnotations.SearchStrategy#INHERITED_ANNOTATIONS
做补充
MergedAnnotations
文章链接
1. 如何使用jdk的api获取父类上的注解?
其实jdk是可以获取父类上的注解的,但是有一个条件,那就是作用于父类上的注解必须使用@Inherited
标识
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface NoneInheritedAnno {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface InheritedAnno {
}
@InheritedAnno
@NoneInheritedAnno
class InheritedClass1 {
}
class InheritedSubClass1 extends InheritedClass1 {
}
@Test
public void jdk_inherited() throws Exception {
// 1. 子类无法获取@NoneInheritedAnno
assertNull(InheritedSubClass1.class.getAnnotation(NoneInheritedAnno.class));
// 2. 子类可以获取@InheritedAnno
assertNotNull(InheritedSubClass1.class.getAnnotation(InheritedAnno.class));
}
2. 使用SearchStrategy.INHERITED_ANNOTATIONS获取父类上的注解
@Test
public void spring_inherited() throws Exception {
assertFalse(
MergedAnnotations.from(InheritedSubClass1.class, SearchStrategy.INHERITED_ANNOTATIONS)
.isPresent(NoneInheritedAnno.class)
);
assertTrue(
MergedAnnotations.from(InheritedSubClass1.class, SearchStrategy.INHERITED_ANNOTATIONS)
.isPresent(InheritedAnno.class)
);
}
3. SearchStrategy.INHERITED_ANNOTATIONS和SearchStrategy.SUPERCLASS的区别
场景 | INHERITED | SUPERCLASS |
---|---|---|
获取父类有@Inherited 的注解 | √ | √ |
获取父类无@Inherited 的注解 | × | √ |
获取接口上的注解 | × | × |