在我们日常的java开发或学习中,经常看到很多注解都被@Inherited进行了修饰,但是这个@Inherited有什么作用呢?下面来分析一下。
Inherited 英文译为“继承”,我么可先理解标注了@Inherited的注解可以被继承,而未标注@Inherited的注解不可被继承,那具体什么场景下注解可被继承呢?有以下几种场景:
注解继承分为两种情况:
- 类级别 Type (Class, Interface),
- 属性和方法级别 (Property, Method)
1、在类继承关系中:子类会继承获得父类上的那些被@Inherited修饰的注解。
2、接口继承关系中:子接口不能继承父接口中的任何注解,不管父接口上使用的注解有没有被@Inherited修饰。
3、在类实现接口时:不会继承任何接口中定义的注解,不管父接口上使用的注解有没有被@Inherited修饰。
4、属性和方法级别 (Property, Method): 注解无论何时都会被子类或子接口继承, 除非子类或子接口重写。
以下为测试代码:我们定义两个注解 @IsInheritedAnnotation 、@NoInherritedAnnotation。其中@IsInheritedAnnotation加了注解@Inherited,@IsInheritedAnnotation注解可被继承。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface IsInheritedAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface NoInherritedAnnotation {
}
@NoInherritedAnnotation
@IsInheritedAnnotation
public class InheritedBase {
}
public class MyInheritedClass extends InheritedBase {
}
@NoInherritedAnnotation
@IsInheritedAnnotation
public interface IInheritedInterface {
}
public interface IInheritedInterfaceChild extends IInheritedInterface {
}
public class MyInheritedClassUseInterface implements IInheritedInterface {
}
// 测试代码
@Test
public void testInherited(){
{
Annotation[] annotations = MyInheritedClass.class.getAnnotations();
assertTrue("", Arrays.stream(annotations).anyMatch(l -> l.annotationType().equals(IsInheritedAnnotation.class)));
assertTrue("", Arrays.stream(annotations).noneMatch(l -> l.annotationType().equals(NoInherritedAnnotation.class)));
}
{
Annotation[] annotations = MyInheritedClassUseInterface.class.getAnnotations();
assertTrue("", Arrays.stream(annotations).noneMatch(l -> l.annotationType().equals(IsInheritedAnnotation.class)));
assertTrue("", Arrays.stream(annotations).noneMatch(l -> l.annotationType().equals(NoInherritedAnnotation.class)));
}
{
Annotation[] annotations = IInheritedInterface.class.getAnnotations();
assertTrue("", Arrays.stream(annotations).anyMatch(l -> l.annotationType().equals(IsInheritedAnnotation.class)));
assertTrue("", Arrays.stream(annotations).anyMatch(l -> l.annotationType().equals(NoInherritedAnnotation.class)));
}
{
Annotation[] annotations = IInheritedInterfaceChild.class.getAnnotations();
assertTrue("", Arrays.stream(annotations).noneMatch(l -> l.annotationType().equals(IsInheritedAnnotation.class)));
assertTrue("", Arrays.stream(annotations).noneMatch(l -> l.annotationType().equals(NoInherritedAnnotation.class)));
}
}