首页  >  文章  >  Java  >  如何在java项目中使用@Inherited元注解

如何在java项目中使用@Inherited元注解

王林
王林转载
2023-05-10 13:34:06902浏览

1.先看源码文档

@已记录

@Retention(保留策略。RUNTIME)

@Target(ElementType。注释类型)

public@interfaceInherited{

}以上代码标注部分可以用Google翻译。大致意思是

指示批注类型的自动继承。如果在标注类型声明中有继承的元标注,用户在类声明上查询标注类型,而类声明没有这个类型的标注,那么类的超类会自动查询标注类型。这个过程将重复进行,直到找到这种类型的注释或者到达类层次结构的顶部。如果没有一个超类有这种类型的注释,查询将会指出这个类没有这样的注释。

请注意,如果您使用注释类型来注释除类之外的任何东西,这种元注释类型没有任何效果。还要注意,这个元注释只会导致从超类继承注释;对已实现接口的无效注释。

从上面的描述可以看出,使用这个标注的标注父类的子类可以继承父类的标注。

2.代码测试

2.1拥有@Inherited注解

@Target(ElementType。类型)

@Retention(保留策略。RUNTIME)

@继承

public  @ interfaceInheritedTest  {

string  value();

}@InheritedTest('拥有继承')

publicclassPerson{

publicvoidmethod(){

}

publicvoidmethod2(){

}

} publicclassstudentextends  person  {

}测试:

publicclassTestInherited{

public  static  void  main(String[]args){

CLaSS  studentCLaSS=student  . class;

if(student  class  . is  notationpresent(inherited  test  . class)){

system  . out  . println(StudentClass  . GetAnnotation(InheritedTest  . Class))。value());

}

}

}输出:

如何在java项目中使用@Inherited元注解

2.2没有@Inherited注释

@Target(ElementType。类型)

@Retention(保留策略。RUNTIME)

public  @ interfacesinotinherited  {

string  value();

} @ IsNotInherited('未拥有继承')

publicclassPerson{

publicvoidmethod(){

}

publicvoidmethod2(){

}

} publicclassstudentextends  person  {

}测试:

publicclassTestInherited{

public  static  void  main(String[]args){

CLaSS  studentCLaSS=student  . class;

if(StudentClass  . is  notationPresent(iSnotinerIded  . Class)){

system  . out  . println(StudentClass  . GetAnnotation(iSNOTiHerided  . class))。value());

}

}

}如何在java项目中使用@Inherited元注解

不输出容差,可见没有@Inherited标注的类的子类不会继承该标注。

以上是如何在java项目中使用@Inherited元注解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除