@Inherited

  在注解上使用@Inherited 表示该注解会被子类继承,注意,仅针对类,成员属性、方法并不受此注释的影响

       测试代码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface InheritedAnnotation {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface NoInheritedAnnotation {
}

@InheritedAnnotation
@NoInheritedAnnotation
public class InheritedBase {
}

public class MyInheritedClass extends InheritedBase {
}

  单元测试

public class MyInheritedClassTest {

    @Test
    public void testMyInheritedClass() {
        Annotation[] annotations = MyInheritedClass.class.getAnnotations();
        boolean isInherited = Arrays.stream(annotations).anyMatch(l -> l.annotationType().equals(InheritedAnnotation.class));  //true
        boolean isNoInherited = Arrays.stream(annotations).anyMatch(l -> l.annotationType().equals(NoInheritedAnnotation.class));  //false
        System.out.println(isInherited+" "+isNoInherited);
    }
}

  

posted on 2020-05-23 11:28  溪水静幽  阅读(280)  评论(0)    收藏  举报