栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中使用@inherited注释?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中使用@inherited注释?

只是没有误会:您确实要询问java.lang.annotation.Inherited。这是注解的注解,这意味着被注解的类的子类被认为具有与其父类相同的注解。

考虑以下2个注释:

@Inherited@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface InheritedAnnotationType {}

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface UninheritedAnnotationType {}

如果像这样注释了三个类:

@UninheritedAnnotationTypeclass A {}@InheritedAnnotationTypeclass B extends A {}class C extends B {}

运行此代码

System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class));System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class));System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class));System.out.println("_________________________________");System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class));System.out.println(new B().getClass().getAnnotation(UninheritedAnnotationType.class));System.out.println(new C().getClass().getAnnotation(UninheritedAnnotationType.class));

将打印与此类似的结果(取决于注释的包):

null@InheritedAnnotationType()@InheritedAnnotationType()_________________________________@UninheritedAnnotationType()nullnull

正如你所看到的

UninheritedAnnotationType
是不能继承,但
C
继承注释
InheritedAnnotationType
B

我不知道与此有什么关系。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497554.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号