spring boot: @Retention註解 @Documented 註解 @Inherited 註解
http://www.jb51.net/article/55371.htm
Retention註解
Retention(保留)註解說明,這種類型的註解會被保留到那個階段. 有三個值:
1.RetentionPolicy.SOURCE —— 這種類型的Annotations只在源代碼級別保留,編譯時就會被忽略
2.RetentionPolicy.CLASS —— 這種類型的Annotations編譯時被保留,在class文件中存在,但JVM將會忽略
3.RetentionPolicy.RUNTIME —— 這種類型的Annotations將被JVM保留,所以他們能在運行時被JVM或其他使用反射機制的代碼所讀取和使用.
示例5演示了 RetentionPolicy.RUNTIME 的聲明:
Java註解的示例1:
@Retention(RetentionPolicy.RUNTIME) public @interface Test_Retention { String doTestRetention(); }
在這個示例中, @Retention(RetentionPolicy.RUNTIME)註解表明 Test_Retention註解將會由虛擬機保留,以便它可以在運行時通過反射讀取.
Documented 註解
Documented 註解表明這個註解應該被 javadoc工具記錄. 默認情況下,javadoc是不包括註解的. 但如果聲明註解時指定了 @Documented,則它會被 javadoc 之類的工具處理, 所以註解類型信息也會被包括在生成的文檔中. 示例6進一步演示了使用 @Documented:
Java註解的示例2:
@Documented public @interface Test_Documented { String doTestDocument(); }
接下來,像下面這樣修改TestAnnotations類:
public class TestAnnotations { public static void main(String arg[]) { new TestAnnotations().doSomeTestRetention(); new TestAnnotations().doSomeTestDocumented(); } @Test_Retention (doTestRetention="保留註解信息測試") public void doSomeTestRetention() { System.out.printf("測試註解類型 ‘Retention‘"); } @Test_Documented(doTestDocument="Hello document") public void doSomeTestDocumented() { System.out.printf("測試註解類型 ‘Documented‘"); } }
現在,如果你使用 javadoc命令生成 TestAnnotations.html文件,你將看到類似於圖1的結果.
從截圖可以看到,文檔中沒有 doSomeTestRetention() 方法的 annotation-type信息()方法. 但是, doSomeTestDocumented() 方法的文檔提供了註解的描述信息. 這是因為 @Documented標簽被加到了Test_Documented註解上. 之前的註解Test_Retention並沒有指定 @Documented 標記(tag).
Inherited 註解(這段可能有問題...)
這是一個稍微復雜的註解類型. 它指明被註解的類會自動繼承. 更具體地說,如果定義註解時使用了 @Inherited 標記,然後用定義的註解來標註另一個父類, 父類又有一個子類(subclass),則父類的所有屬性將被繼承到它的子類中. 在示例7中,你會看到使用 @Inherited 標簽的好處.
Java註解的示例3
首先,定義你的註解:
@Inherited public @interface MyParentObject { boolean isInherited() default true; String doSomething() default "Do what?"; }
接下來,使用註解標註了一個類:
@MyParentObject public Class MyChildObject { }
正如你看到的,你不需要在實現類中定義接口方法. 因為使用 @Inherited標記,這些都自動繼承了. 如果你使用一種古老的方式定義實現類,會是什麽樣子呢? 看看下面這張 古老的實現方式吧:
public class MyChildObject implements MyParentObject { public boolean isInherited() { return false; } public String doSomething() { return ""; } public boolean equals(Object obj) { return false; } public int hashCode() { return 0; } public String toString() { return ""; } public Class annotationType() { return null; } }
看到的區別嗎? 可以看到,你必須實現父接口的所有方法. 除了isInherited()和從myParentObject doSomething()方法外,你還需要實現 java.lang.Object的 equals(),toString()和hasCode()方法. 還有 java.lang.annotation.Annotation 類的 annotationType()方法. 不管你是不是想要實現這些方法,你必須在繼承的對象中包含這些.
spring boot: @Retention註解 @Documented 註解 @Inherited 註解