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

Str*_*der 49 java inheritance annotations

我没有@Inherited在Java中获得注释.如果它自动为你继承了这些方法,那么如果我需要以自己的方式实现该方法那么那么呢?

如何了解我的实施方式?

再加上它是说,如果我不想用这个,做它,而在一个老式的Java办法,我必须实现的equals(),toString()以及hashCode()该方法的Object类,也是的注释类型的方法java.lang.annotation.Annotation类.

这是为什么?

即使我不知道@Inherited注释和用于工作的程序,我也从未实现过.

请有人从头开始解释我这件事.

fab*_*ian 95

只是没有误解:你确实问过java.lang.annotation.Inherited.这是注释的注释.这意味着注释类的子类被认为与它们的超类具有相同的注释.

考虑以下2个注释:

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

}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

如果三个类注释如下:

@UninheritedAnnotationType
class A {

}

@InheritedAnnotationType
class B extends A {

}

class C extends B {

}
Run Code Online (Sandbox Code Playgroud)

运行此代码

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));
Run Code Online (Sandbox Code Playgroud)

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

null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样,UninheritedAnnotationType它不是继承的,而是从中C继承注释.InheritedAnnotationTypeB

我不知道有什么方法与此有关.

  • @saurabh实际上,这对于接口不起作用,请参见javadoc https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Inherited.html:*“如果继承了元注释, ”出现在注释类型声明上,并且用户在类声明上查询注释类型,并且该类声明没有该类型的注释,则将自动查询该类的超类以获取注释类型。“ *(类的层次结构是“一行”,如果您也考虑使用接口,它可能会变成“一棵树”,从而导致查找效率低和/或冲突。) (3认同)
  • 这对于类非常有用,但是如果它们是接口,为什么不呢?只是使类A,B,C作为接口并使用C.class.getAnnotation(InheritedAnnotationType.class),它将无法正常工作? (2认同)
  • 我们还可以使用A.class.isAnnotationPresent(InheritedAnnotationType.class)简化测试,该测试将返回一个布尔值。 (2认同)
  • @saurabh 我知道这个旧但因为它仍然相关,文档状态:_"请注意,如果注释类型用于注释除类以外的任何内容,则此元注释类型无效。另请注意,此元注释仅导致从超类继承注解;已实现接口上的注解不起作用。”_ (2认同)