如何在Java中使用@inherited注释? [英] How to use @inherited annotation in Java?
问题描述
我没有在Java中获得 @Inherited
注释。如果它自动为你继承了这些方法,那么如果我需要以我自己的方式实现该方法那么那么呢?
I am not getting the @Inherited
annotation in Java. If it automatically inherits the methods for you then if I need to implement the method in my own way then what about that ?
如何知道我的方式呢?实现?
How does will it come to know my way of implementation ?
另外有人说,如果我不想使用它,而是采用老式的Java方式,我必须实现 equals()
, toString()
,以及 hashCode()
方法 Object
class以及 java.lang.annotation.Annotation
类的注释类型方法。
Plus it is said if I do not want to use this and do it rather in an old fashioned Java way I have to implement the the equals()
, toString()
, and the hashCode()
methods of the Object
class and also the annotation type method of the java.lang.annotation.Annotation
class.
为什么会这样?
即使我不知道 @Inherited,我也从未实现过这些
注释和用于正常工作的程序。
I have never implemented those even when I did not know about the @Inherited
annotation and the programs used to work fine also .
请有人从头开始解释我这个问题。
Please somebody explain me from the scratch about this.
推荐答案
只是没有误解:你确实问过 java.lang.annotation.Inherited 。这是注释的注释。它意味着带注释的类的子类被认为与它们的超类具有相同的注释。
Just that there is no misunderstanding: You do ask about java.lang.annotation.Inherited. This is a annotation for annotations.It means that subclasses of annotated classes are considered having the same annotation as their superclass.
考虑以下2个注释:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {
}
和
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotationType {
}
如果三个班级是注释如下:
If three classes are annotated like this:
@UninheritedAnnotationType
class A {
}
@InheritedAnnotationType
class 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));
将打印与此类似的结果(取决于注释的包):
will print a result similar to this (depending on the packages of the annotation):
null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null
正如您所见 UninheritedAnnotationType
未继承,但 C
从 B <继承注释
InheritedAnnotationType
/ code>。
As you can see UninheritedAnnotationType
is not inherited but C
inherits annotation InheritedAnnotationType
from B
.
我不知道有什么方法与此有关。
这篇关于如何在Java中使用@inherited注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!