java 注解 inherited_java元注解@Inherited的使用详解

1.先看源码文档

/**

* Indicates that an annotation type is automatically inherited. If

* an Inherited meta-annotation is present on an annotation type

* declaration, and the user queries the annotation type on a class

* declaration, and the class declaration has no annotation for this type,

* then the classnDCoiuF's superclass will automatically be queried for the

* annotation type. This process will be repeated until an annwww.cppcns.com;Note that this meta-annotation type has no effect if the annotated

* type is used to annotate anything other than a class. Note also

* that this meta-annotation only causes annotations

上述代码注释部分可以用谷歌翻译大法大致意思是

表示注释类型自动继承。 如果在注释类型声明中存在继承的元注释,并且用户在类声明上查询注释类型,并且类声明没有此类型的注释,则该类的超类将自动查询注释类型。 将重复此过程,直到找到此类型的注释,或者达到类层次结构(Object)的顶部。 如果没有超类具有此类型的注释,则查询将指示所讨

请注意,如果使用注释类型来注释除类之外的任何内容,则此元注释类型不起作用。 还要注意,这个元注释只会导致从超类继承注释; 已实现的接口上的注释无效。

通过上述描述可知,使用该注解的注解父类的子类可以继承父类的注解。

2.代码测试

2.1拥有@Inherited注解

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Inherited

public @interface InheritedTest {

String value();

}

@InheritedTest("拥有Inherited")

public class Person {

public void method(){

}

public void method2(){

}

}

public class Student extends Person {

}

测试:

public class TestInherited {

public static void main(String[] args) {

Class studentClass = Student.class;

if (studentClass.isAnnotationPresent(InheritedTest.class)){

System.out.println(studentClass.getAnnotation(InheritedTest.class).value());

}

}

}

输出:

6efb1868213b9baff2df76e983376279.png

2.2未拥有@Inherited注解

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface IsNotInherited {

String value();

}

@IsNotInherited("未拥有Inherited")

public class Person {

public void method(){

}

public void method2(){

}

}

public class Student extends Person {

}

测试:

public class TestInherited {

public static void main(String[] args) {

Class studentClass = Student.class;

if (studentClass.isAnnotationPresent(IsNotInherited.class)){

System.out.println(studentClass.getAnnotation(IsNotInherited.class).value());

}

}

}

a488cb4e4d5d1502b4e40a998bb95776.png

没有输出任何任容,由此可知未拥有@Inherited注解的注解的类的子类不会被继承该注解。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: java元注解@Inherited的使用详解

本文地址: http://www.cppcns.com/ruanjian/java/289018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值