@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); } }
立志如山 静心求实
浙公网安备 33010602011771号