Java中@Inherited的作用

在我们日常的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)));
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值