java註解學習---@Inherited註解的理解學習(四)
一、 @Inherited 註解的作用
1、 允許子類繼承父類的註解。 (子類中可以獲取並使用父類註解)
二、使用代碼實現思路
1、定義父類註解: @ParentAnnotation 使用 @Inherited 註解標記。
2、定義子類註解: @ChildAnnotation 不使用@Inherited 註解標記。
3、定義一個普通 Parent 類, 使用 @ParentAnnotation 註解標記
4、定義一個普通 Child 類,繼承 Parent 類 , 使用 @ChildAnnotation 註解標記
5、定義一個測試類,根據測試結果,理解 @Inherited 註解。
三、代碼實現
1、 定義 @ParentAnnotation 註解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.TYPE)
@Inherited
public @interface ParentAnnotation {
}
2、定義 @ChildAnnotation 註解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.TYPE)
public @interface ChildAnnotation {
}
3、 定義 Parent 類
@ParentAnnotation
public class Parent {
}
4、定義 Child 類
@ChildAnnotation
public class Child extends Parent {
}
5、測試類
public static void main(String[] args) {
ParentAnnotation parent = Parent.class.getAnnotation(ParentAnnotation.class);
ChildAnnotation parentChild = Parent.class.getAnnotation(ChildAnnotation.class);
System.out.println("parent: "+parent +" parentChild :"+parentChild);
System.out.println(" ===== child test ==== ");
ParentAnnotation childParent = Child.class.getAnnotation(ParentAnnotation.class);
ChildAnnotation child = Child.class.getAnnotation(ChildAnnotation.class);
System.out.println("childParent: "+childParent +" child :"+child);
}
6、 程序運行結果:
parent: @com.haha.study.annotation.inherited.simple.ParentAnnotation() parentChild :null
===== child test ====
childParent: @com.haha.study.annotation.inherited.simple.ParentAnnotation() child :@com.haha.study.annotation.inherited.simple.ChildAnnotation()
7、結果分析: 可以看到 childParent 的結果不是 null , 說明了 Child 類繼承了 Parent 類,也繼承了 Parent 類的標記註解 @ParentAnnotation 。 反之去掉 @ParentAnnotation 註解上的 @Inherited 註解, 再進行測試 , childParent 的結果變成了 null 。
四、 總結
1、 @Inherited 註解的作用: 允許子類繼承父類的註解。 即在兩個類之間存在繼承關係,且父類標記的註解使用了 @Inherited 註解(注: 總感覺這裏表述不清,參考 @ParentAnnotation 註解的定義即可),這時繼承的子類可以使用父類的註解。
2、@Inherited 註解的誤解: 子註解類繼承父註解類 --- @ChildAnnotation 註解類 繼承@ParentAnnotation 註解類。