[英]How to use @inherited annotation in Java?
I am not getting the @Inherited
annotation in Java. 我没有在Java中获得
@Inherited
注释。 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 ? 如何了解我的实施方式?
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. 另外,如果我不想使用它并且以旧式Java方式执行它,我必须实现
Object
类的equals()
, toString()
和hashCode()
方法以及注释。 java.lang.annotation.Annotation
类的type方法。
Why is that? 这是为什么?
I have never implemented those even when I did not know about the @Inherited
annotation and the programs used to work fine also . 即使我不知道
@Inherited
注释和过去工作正常的程序,我也从未实现过。
Please somebody explain me from the scratch about this. 请有人从头开始解释我这件事。
Just that there is no misunderstanding: You do ask about java.lang.annotation.Inherited . 只是没有误解:你确实问过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.
这是注释的注释。这意味着注释类的子类被认为与它们的超类具有相同的注释。
Consider the following 2 Annotations: 考虑以下2个注释:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {
}
and 和
@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 {
}
running this code 运行此代码
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
As you can see UninheritedAnnotationType
is not inherited but C
inherits annotation InheritedAnnotationType
from B
. 如您所见,
UninheritedAnnotationType
不是继承的,但C
从B
继承注释InheritedAnnotationType
。
I don't know what methods have to do with that. 我不知道有什么方法与此有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.