新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

怎么在java项目中使用@Inherited元注解-创新互联

本篇文章给大家分享的是有关怎么在java项目中使用@Inherited元注解,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

创新互联公司专业为企业提供孟津网站建设、孟津做网站、孟津网站设计、孟津网站制作等企业网站建设、网页设计与制作、孟津企业网站模板建站服务,10余年孟津做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

1.先看源码文档

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

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

表示注释类型自动继承。 如果在注释类型声明中存在继承的元注释,并且用户在类声明上查询注释类型,并且类声明没有此类型的注释,则该类的超类将自动查询注释类型。 将重复此过程,直到找到此类型的注释,或者达到类层次结构(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());
    }


  }
}

输出:

怎么在java项目中使用@Inherited元注解

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());
    }


  }
}

怎么在java项目中使用@Inherited元注解

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

以上就是怎么在java项目中使用@Inherited元注解,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联网站建设公司行业资讯频道。

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章标题:怎么在java项目中使用@Inherited元注解-创新互联
标题网址:http://www.wjwzjz.com/article/deoogi.html
在线咨询
服务热线
服务热线:028-86922220
TOP