JAVA注解 | 继承元注解@Inherited的用法

@Inherited 是一个元注解,专门用来修饰注解,被 @Inherited 修饰的注解具备继承传递性。

通过代码来验证,首先创建一个自定义注解,但是不加 @Inherited 修饰

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Version {

    String value() default "1";

}

创建一个父类,使用 @Version 注解

@Version
public class TestParentBean {

    public void sayHello() {
        System.out.println("Hello parent bean");
    }

}

创建一个子类,不使用注解

public class TestBean extends TestParentBean {

    public void sayHello() {
        System.out.println("Hello bean");
    }

}

通过反射查找注解并打印

public class AnnotationTest {

    public static void main(String[] args) throws Exception {
        // 读取当前类及父类的注解
        Annotation[] annotations = TestBean.class.getAnnotations(); 
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        System.out.println("-----------");

        // 读取当前类的注解
        annotations = TestBean.class.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
    }

}

输出结果如下,说明不管是通过 getAnnotations() 方法或者是 getDeclaredAnnotations() 方法,都不能获取到父类的注解。

-----------

现在为 Version 添加 @Inherited 元注解

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Version {

    String value() default "1";

}

再次执行输出结果如下,可以看到 getAnnotations() 是可以获取到父类的有 @Inherited 修饰的注解的,而 getDeclaredAnnotations() 则只能获取当前类的注解。

@test.annotation.Version(value=1)
-----------

注意:@Inherited 的适用范围

1、在接口上使用 @Inherited 修饰的注解,其实现类不会继承这个注解
2、父类的方法上使用 @Inherited 修饰的注解,其子类不会继承这个注解

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`@Inherited` 是一个标准的 Java 注解(meta-annotation),用于指示一个注解是否可以被继承。当一个注解被标注为 `@Inherited` 后,它将可以被子类继承。 具体来说,当一个被 `@Inherited` 标注的注解被放置在一个父类上时,它将会被子类继承,并且子类上也会具有该注解。这意味着,如果我们在父类上使用了一个被 `@Inherited` 标注的注解,那么所有继承该父类的子类也将自动具有该注解。 需要注意的是,`@Inherited` 注解仅对类级别的注解有效,对方法、字段等其他素的注解无效。 下面是一个示例,展示了如何使用 `@Inherited` 注解: ```java import java.lang.annotation.*; @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyAnnotation { // 注解素 String value(); } ``` 在上面的示例中,我们定义了一个自定义注解 `@MyAnnotation` 并标注了 `@Inherited` 注解。当我们将 `@MyAnnotation` 注解放置在一个父类上时,该注解将会被子类继承。 ```java @MyAnnotation("Parent") public class ParentClass { // 父类的代码内容 } public class ChildClass extends ParentClass { // 子类的代码内容 } ``` 在上面的示例中,`ChildClass` 继承自 `ParentClass`,由于 `@MyAnnotation` 使用了 `@Inherited` 注解,所以 `ChildClass` 也会自动具有 `@MyAnnotation("Parent")` 注解。 总结一下,`@Inherited` 是一个注解,用于指示一个注解是否可以被继承。当一个注解被标注为 `@Inherited` 后,它将可以被子类继承。但需要注意,它仅对类级别的注解有效,对其他素的注解无效。 希望能够解答你的疑问。如果还有其他问题,请随时提问。谢谢!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值