簡體   English   中英

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

[英]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不是繼承的,但CB繼承注釋InheritedAnnotationType

我不知道有什么方法與此有關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM