首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中使用@inherited注解?

如何在Java中使用@inherited注解?
EN

Stack Overflow用户
提问于 2014-06-01 01:05:02
回答 1查看 41.8K关注 0票数 64

我在Java语言中没有得到@Inherited注解。如果它自动为您继承方法,那么如果我需要以自己的方式实现该方法,那该怎么办呢?

它如何知道我的实现方式?

另外,据说如果我不想使用它,而是以一种老式的Java方式来实现,我必须实现Object类的equals()toString()hashCode()方法,以及java.lang.annotation.Annotation类的注释类型方法。

为什么会这样呢?

我从来没有实现过这些,即使我不知道@Inherited注解,程序也可以很好地工作。

请有人从头给我解释一下这件事。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-01 01:42:36

只是没有误解:你确实问了关于java.lang.annotation.Inherited的问题。这是annotations.It的一个注解,这意味着带注解的类的子类被认为具有与其超类相同的注解。

示例

考虑以下两个注释:

代码语言:javascript
复制
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {
    
}

代码语言:javascript
复制
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotationType {
    
}

如果有三个类是这样注释的:

代码语言:javascript
复制
@UninheritedAnnotationType
class A {
    
}

@InheritedAnnotationType
class B extends A {
    
}

class C extends B {
    
}

运行此代码

代码语言:javascript
复制
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));

将打印类似以下内容的结果(取决于注释的包):

代码语言:javascript
复制
null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null

正如您所看到的,UninheritedAnnotationType不是继承的,但是CB继承了注释InheritedAnnotationType

我不知道有什么方法可以解决这个问题。

票数 126
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23973107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档