[英]How to use @inherited annotation in Java?
我沒有在Java中獲得@Inherited
注釋。 如果它自動為你繼承了這些方法,那么如果我需要以自己的方式實現該方法那么那么呢?
如何了解我的實施方式?
另外,如果我不想使用它並且以舊式Java方式執行它,我必須實現Object
類的equals()
, toString()
和hashCode()
方法以及注釋。 java.lang.annotation.Annotation
類的type方法。
這是為什么?
即使我不知道@Inherited
注釋和過去工作正常的程序,我也從未實現過。
請有人從頭開始解釋我這件事。
只是沒有誤解:你確實問過java.lang.annotation.Inherited 。 這是注釋的注釋。這意味着注釋類的子類被認為與它們的超類具有相同的注釋。
考慮以下2個注釋:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {
}
和
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotationType {
}
如果三個類注釋如下:
@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));
將打印與此類似的結果(取決於注釋的包):
null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null
如您所見, UninheritedAnnotationType
不是繼承的,但C
從B
繼承注釋InheritedAnnotationType
。
我不知道有什么方法與此有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.