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
我不知道有什么方法与此有关.