https://www.cnblogs.com/skywang12345/p/3344137.html
https://www.runoob.com/w3cnote/java-annotation.html
Java 注解(Annotation)
分類 編程技術(shù)
Java 注解(Annotation)又稱 Java 標(biāo)注,是 JDK5.0 引入的一種注釋機(jī)制。
Java 語(yǔ)言中的類、方法、變量、參數(shù)和包等都可以被標(biāo)注。和 Javadoc 不同,Java 標(biāo)注可以通過(guò)反射獲取標(biāo)注內(nèi)容。在編譯器生成類文件時(shí),標(biāo)注可以被嵌入到字節(jié)碼中。Java 虛擬機(jī)可以保留標(biāo)注內(nèi)容,在運(yùn)行時(shí)可以獲取到標(biāo)注內(nèi)容 。 當(dāng)然它也支持自定義 Java 標(biāo)注。
網(wǎng)上很多關(guān)于 Java Annotation 的文章,看得人眼花繚亂。Java Annotation 本來(lái)很簡(jiǎn)單的,結(jié)果說(shuō)的人沒(méi)說(shuō)清楚;弄的看的人更加迷糊。
我按照自己的思路,對(duì) Annotation 進(jìn)行了整理。理解 Annotation 的關(guān)鍵,是理解 Annotation 的語(yǔ)法和用法,對(duì)這些內(nèi)容,我都進(jìn)行了詳細(xì)說(shuō)明;理解 Annotation 的語(yǔ)法和用法之后,再看 Annotation 的框架圖,可能有更深刻體會(huì)。廢話就說(shuō)這么多,下面開(kāi)始對(duì) Annotation 進(jìn)行說(shuō)明。若您發(fā)現(xiàn)文章中存在錯(cuò)誤或不足的地方,希望您能指出!
內(nèi)置的注解
Java 定義了一套注解,共有 7 個(gè),3 個(gè)在 java.lang 中,剩下 4 個(gè)在 java.lang.annotation 中。
作用在代碼的注解是
- @Override - 檢查該方法是否是重寫方法。如果發(fā)現(xiàn)其父類,或者是引用的接口中并沒(méi)有該方法時(shí),會(huì)報(bào)編譯錯(cuò)誤。
- @Deprecated - 標(biāo)記過(guò)時(shí)方法。如果使用該方法,會(huì)報(bào)編譯警告。
- @SuppressWarnings - 指示編譯器去忽略注解中聲明的警告。
作用在其他注解的注解(或者說(shuō) 元注解)是:
- @Retention - 標(biāo)識(shí)這個(gè)注解怎么保存,是只在代碼中,還是編入class文件中,或者是在運(yùn)行時(shí)可以通過(guò)反射訪問(wèn)。
- @Documented - 標(biāo)記這些注解是否包含在用戶文檔中。
- @Target - 標(biāo)記這個(gè)注解應(yīng)該是哪種 Java 成員。
- @Inherited - 標(biāo)記這個(gè)注解是繼承于哪個(gè)注解類(默認(rèn) 注解并沒(méi)有繼承于任何子類)
從 Java 7 開(kāi)始,額外添加了 3 個(gè)注解:
- @SafeVarargs - Java 7 開(kāi)始支持,忽略任何使用參數(shù)為泛型變量的方法或構(gòu)造函數(shù)調(diào)用產(chǎn)生的警告。
- @FunctionalInterface - Java 8 開(kāi)始支持,標(biāo)識(shí)一個(gè)匿名函數(shù)或函數(shù)式接口。
- @Repeatable - Java 8 開(kāi)始支持,標(biāo)識(shí)某注解可以在同一個(gè)聲明上使用多次。
1、Annotation 架構(gòu)

從中,我們可以看出:
(01) 1 個(gè) Annotation 和 1 個(gè) RetentionPolicy 關(guān)聯(lián)。
可以理解為:每1個(gè)Annotation對(duì)象,都會(huì)有唯一的RetentionPolicy屬性。
(02) 1 個(gè) Annotation 和 1~n 個(gè) ElementType 關(guān)聯(lián)。
可以理解為:對(duì)于每 1 個(gè) Annotation 對(duì)象,可以有若干個(gè) ElementType 屬性。
(03) Annotation 有許多實(shí)現(xiàn)類,包括:Deprecated, Documented, Inherited, Override 等等。
Annotation 的每一個(gè)實(shí)現(xiàn)類,都 "和 1 個(gè) RetentionPolicy 關(guān)聯(lián)" 并且 " 和 1~n 個(gè) ElementType 關(guān)聯(lián)"。
下面,我先介紹框架圖的左半邊(如下圖),即 Annotation, RetentionPolicy, ElementType;然后在就 Annotation 的實(shí)現(xiàn)類進(jìn)行舉例說(shuō)明。

2、Annotation 組成部分
java Annotation 的組成中,有 3 個(gè)非常重要的主干類。它們分別是:
Annotation.java
package java.lang.annotation;
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
ElementType.java
package java.lang.annotation;
public enum ElementType {
TYPE, /* 類、接口(包括注釋類型)或枚舉聲明 */
FIELD, /* 字段聲明(包括枚舉常量) */
METHOD, /* 方法聲明 */
PARAMETER, /* 參數(shù)聲明 */
CONSTRUCTOR, /* 構(gòu)造方法聲明 */
LOCAL_VARIABLE, /* 局部變量聲明 */
ANNOTATION_TYPE, /* 注釋類型聲明 */
PACKAGE /* 包聲明 */
}
RetentionPolicy.java
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE, /* Annotation信息僅存在于編譯器處理期間,編譯器處理完之后就沒(méi)有該Annotation信息了 */
CLASS, /* 編譯器將Annotation存儲(chǔ)于類對(duì)應(yīng)的.class文件中。默認(rèn)行為 */
RUNTIME /* 編譯器將Annotation存儲(chǔ)于class文件中,并且可由JVM讀入 */
}
說(shuō)明:
(01) Annotation 就是個(gè)接口。
"每 1 個(gè) Annotation" 都與 "1 個(gè) RetentionPolicy" 關(guān)聯(lián),并且與 "1~n 個(gè) ElementType" 關(guān)聯(lián)??梢酝ㄋ椎睦斫鉃椋好?1 個(gè) Annotation 對(duì)象,都會(huì)有唯一的 RetentionPolicy 屬性;至于 ElementType 屬性,則有 1~n 個(gè)。
(02) ElementType 是 Enum 枚舉類型,它用來(lái)指定 Annotation 的類型。
"每 1 個(gè) Annotation" 都與 "1~n 個(gè) ElementType" 關(guān)聯(lián)。當(dāng) Annotation 與某個(gè) ElementType 關(guān)聯(lián)時(shí),就意味著:Annotation有了某種用途。例如,若一個(gè) Annotation 對(duì)象是 METHOD 類型,則該 Annotation 只能用來(lái)修飾方法。
(03) RetentionPolicy 是 Enum 枚舉類型,它用來(lái)指定 Annotation 的策略。通俗點(diǎn)說(shuō),就是不同 RetentionPolicy 類型的 Annotation 的作用域不同。
"每 1 個(gè) Annotation" 都與 "1 個(gè) RetentionPolicy" 關(guān)聯(lián)。
- a) 若 Annotation 的類型為 SOURCE,則意味著:Annotation 僅存在于編譯器處理期間,編譯器處理完之后,該 Annotation 就沒(méi)用了。 例如," @Override" 標(biāo)志就是一個(gè) Annotation。當(dāng)它修飾一個(gè)方法的時(shí)候,就意味著該方法覆蓋父類的方法;并且在編譯期間會(huì)進(jìn)行語(yǔ)法檢查!編譯器處理完后,"@Override" 就沒(méi)有任何作用了。
- b) 若 Annotation 的類型為 CLASS,則意味著:編譯器將 Annotation 存儲(chǔ)于類對(duì)應(yīng)的 .class 文件中,它是 Annotation 的默認(rèn)行為。
- c) 若 Annotation 的類型為 RUNTIME,則意味著:編譯器將 Annotation 存儲(chǔ)于 class 文件中,并且可由JVM讀入。
這時(shí),只需要記住"每 1 個(gè) Annotation" 都與 "1 個(gè) RetentionPolicy" 關(guān)聯(lián),并且與 "1~n 個(gè) ElementType" 關(guān)聯(lián)。學(xué)完后面的內(nèi)容之后,再回頭看這些內(nèi)容,會(huì)更容易理解。
3、java 自帶的 Annotation
理解了上面的 3 個(gè)類的作用之后,我們接下來(lái)可以講解 Annotation 實(shí)現(xiàn)類的語(yǔ)法定義了。
1)Annotation 通用定義
<pre class="prettyprint prettyprinted" style="">@Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation1 { }</pre>
說(shuō)明:
上面的作用是定義一個(gè) Annotation,它的名字是 MyAnnotation1。定義了 MyAnnotation1 之后,我們可以在代碼中通過(guò) "@MyAnnotation1" 來(lái)使用它。 其它的,@Documented, @Target, @Retention, @interface 都是來(lái)修飾 MyAnnotation1 的。下面分別說(shuō)說(shuō)它們的含義:
(01) @interface
使用 @interface 定義注解時(shí),意味著它實(shí)現(xiàn)了 java.lang.annotation.Annotation 接口,即該注解就是一個(gè)Annotation。
定義 Annotation 時(shí),@interface 是必須的。
注意:它和我們通常的 implemented 實(shí)現(xiàn)接口的方法不同。Annotation 接口的實(shí)現(xiàn)細(xì)節(jié)都由編譯器完成。通過(guò) @interface 定義注解后,該注解不能繼承其他的注解或接口。
(02) @Documented
類和方法的 Annotation 在缺省情況下是不出現(xiàn)在 javadoc 中的。如果使用 @Documented 修飾該 Annotation,則表示它可以出現(xiàn)在 javadoc 中。
定義 Annotation 時(shí),@Documented 可有可無(wú);若沒(méi)有定義,則 Annotation 不會(huì)出現(xiàn)在 javadoc 中。
(03) @Target(ElementType.TYPE)
前面我們說(shuō)過(guò),ElementType 是 Annotation 的類型屬性。而 @Target 的作用,就是來(lái)指定 Annotation 的類型屬性。
@Target(ElementType.TYPE) 的意思就是指定該 Annotation 的類型是 ElementType.TYPE。這就意味著,MyAnnotation1 是來(lái)修飾"類、接口(包括注釋類型)或枚舉聲明"的注解。
定義 Annotation 時(shí),@Target 可有可無(wú)。若有 @Target,則該 Annotation 只能用于它所指定的地方;若沒(méi)有 @Target,則該 Annotation 可以用于任何地方。
(04) @Retention(RetentionPolicy.RUNTIME)
前面我們說(shuō)過(guò),RetentionPolicy 是 Annotation 的策略屬性,而 @Retention 的作用,就是指定 Annotation 的策略屬性。
@Retention(RetentionPolicy.RUNTIME) 的意思就是指定該 Annotation 的策略是 RetentionPolicy.RUNTIME。這就意味著,編譯器會(huì)將該 Annotation 信息保留在 .class 文件中,并且能被虛擬機(jī)讀取。
定義 Annotation 時(shí),@Retention 可有可無(wú)。若沒(méi)有 @Retention,則默認(rèn)是 RetentionPolicy.CLASS。
2)java自帶的Annotation
通過(guò)上面的示例,我們能理解:@interface 用來(lái)聲明 Annotation,@Documented 用來(lái)表示該 Annotation 是否會(huì)出現(xiàn)在 javadoc 中, @Target 用來(lái)指定 Annotation 的類型,@Retention 用來(lái)指定 Annotation 的策略。
理解這一點(diǎn)之后,我們就很容易理解 java 中自帶的 Annotation 的實(shí)現(xiàn)類,即 Annotation 架構(gòu)圖的右半邊。如下圖:

java 常用的 Annotation:
<pre class="prettyprint prettyprinted" style="">@Deprecated -- @Deprecated 所標(biāo)注內(nèi)容,不再被建議使用。 @Override -- @Override 只能標(biāo)注方法,表示該方法覆蓋父類中的方法。 @Documented -- @Documented 所標(biāo)注內(nèi)容,可以出現(xiàn)在javadoc中。 @Inherited -- @Inherited只能被用來(lái)標(biāo)注“Annotation類型”,它所標(biāo)注的Annotation具有繼承性。 @Retention -- @Retention只能被用來(lái)標(biāo)注“Annotation類型”,而且它被用來(lái)指定Annotation的RetentionPolicy屬性。 @Target -- @Target只能被用來(lái)標(biāo)注“Annotation類型”,而且它被用來(lái)指定Annotation的ElementType屬性。 @SuppressWarnings -- @SuppressWarnings 所標(biāo)注內(nèi)容產(chǎn)生的警告,編譯器會(huì)對(duì)這些警告保持靜默。</pre>
由于 "@Deprecated 和 @Override" 類似,"@Documented, @Inherited, @Retention, @Target" 類似;下面,我們只對(duì) @Deprecated, @Inherited, @SuppressWarnings 這 3 個(gè) Annotation 進(jìn)行說(shuō)明。
2.1) @Deprecated
@Deprecated 的定義如下:
<pre class="prettyprint prettyprinted" style="">@Documented @Retention(RetentionPolicy.RUNTIME) public @interface Deprecated { }</pre>
說(shuō)明:
- (01) @interface -- 它的用來(lái)修飾 Deprecated,意味著 Deprecated 實(shí)現(xiàn)了 java.lang.annotation.Annotation 接口;即 Deprecated 就是一個(gè)注解。 (02) @Documented -- 它的作用是說(shuō)明該注解能出現(xiàn)在 javadoc 中。
- (03) @Retention(RetentionPolicy.RUNTIME) -- 它的作用是指定 Deprecated 的策略是 RetentionPolicy.RUNTIME。這就意味著,編譯器會(huì)將Deprecated 的信息保留在 .class 文件中,并且能被虛擬機(jī)讀取。
- (04) @Deprecated 所標(biāo)注內(nèi)容,不再被建議使用。
例如,若某個(gè)方法被 @Deprecated 標(biāo)注,則該方法不再被建議使用。如果有開(kāi)發(fā)人員試圖使用或重寫被 @Deprecated 標(biāo)示的方法,編譯器會(huì)給相應(yīng)的提示信息。示例如下:

DeprecatedTest.java
import java.util.Date;
import java.util.Calendar;
public class DeprecatedTest {
// @Deprecated 修飾 getString1(),表示 它是建議不被使用的函數(shù)
@Deprecated
private static void getString1(){
System.out.println("Deprecated Method");
}
private static void getString2(){
System.out.println("Normal Method");
}
// Date是日期/時(shí)間類。java已經(jīng)不建議使用該類了
private static void testDate() {
Date date = new Date(113, 8, 25);
System.out.println(date.getYear());
}
// Calendar是日期/時(shí)間類。java建議使用Calendar取代Date表示"日期/時(shí)間"
private static void testCalendar() {
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.YEAR));
}
public static void main(String[] args) {
getString1();
getString2();
testDate();
testCalendar();
}
}
說(shuō)明:
上面是 eclipse 中的截圖,比較類中 "getString1() 和 getString2()" 以及 "testDate() 和 testCalendar()" 。
(01) getString1() 被 @Deprecated 標(biāo)注,意味著建議不再使用 getString1(); 所以 getString1() 的定義和調(diào)用時(shí),都會(huì)一橫線。這一橫線是eclipse() 對(duì) @Deprecated 方法的處理。
getString2() 沒(méi)有被 @Deprecated 標(biāo)注,它的顯示正常。
(02) testDate() 調(diào)用了 Date 的相關(guān)方法,而 java 已經(jīng)建議不再使用 Date 操作日期/時(shí)間。因此,在調(diào)用 Date的API 時(shí),會(huì)產(chǎn)生警告信息,途中的 warnings。
testCalendar() 調(diào)用了 Calendar 的 API 來(lái)操作日期/時(shí)間,java 建議用 Calendar 取代 Date。因此,操作 Calendar 不會(huì)產(chǎn)生 warning。
2.2) @Inherited
@Inherited 的定義如下:
<pre class="prettyprint prettyprinted" style="">@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Inherited { }</pre>
說(shuō)明:
- (01) @interface -- 它的用來(lái)修飾 Inherited,意味著 Inherited 實(shí)現(xiàn)了 java.lang.annotation.Annotation 接口;即 Inherited 就是一個(gè)注解。
- (02) @Documented -- 它的作用是說(shuō)明該注解能出現(xiàn)在 javadoc 中。
- (03) @Retention(RetentionPolicy.RUNTIME) -- 它的作用是指定 Inherited 的策略是 RetentionPolicy.RUNTIME。這就意味著,編譯器會(huì)將 Inherited 的信息保留在 .class 文件中,并且能被虛擬機(jī)讀取。
- (04) @Target(ElementType.ANNOTATION_TYPE) -- 它的作用是指定 Inherited 的類型是 ANNOTATION_TYPE。這就意味著,@Inherited 只能被用來(lái)標(biāo)注 "Annotation 類型"。
- (05) @Inherited 的含義是,它所標(biāo)注的Annotation將具有繼承性。
假設(shè),我們定義了某個(gè) Annotaion,它的名稱是 MyAnnotation,并且 MyAnnotation 被標(biāo)注為 @Inherited。現(xiàn)在,某個(gè)類 Base 使用了
MyAnnotation,則 Base 具有了"具有了注解 MyAnnotation";現(xiàn)在,Sub 繼承了 Base,由于 MyAnnotation 是 @Inherited的(具有繼承性),所以,Sub 也 "具有了注解 MyAnnotation"。
@Inherited 的使用示例:
InheritableSon.java
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Inherited;
/**
- 自定義的Annotation。
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface Inheritable
{
}
@Inheritable
class InheritableFather
{
public InheritableFather() {
// InheritableBase是否具有 Inheritable Annotation
System.out.println("InheritableFather:"+InheritableFather.class.isAnnotationPresent(Inheritable.class));
}
}
/**
-
InheritableSon 類只是繼承于 InheritableFather,
*/
public class InheritableSon extends InheritableFather
{
public InheritableSon() {
super(); // 調(diào)用父類的構(gòu)造函數(shù)
// InheritableSon類是否具有 Inheritable Annotation
System.out.println("InheritableSon:"+InheritableSon.class.isAnnotationPresent(Inheritable.class));
}public static void main(String[] args)
{
InheritableSon is = new InheritableSon();
}
}
運(yùn)行結(jié)果:
<pre class="prettyprint prettyprinted" style="">InheritableFather:true InheritableSon:true</pre>
現(xiàn)在,我們對(duì) InheritableSon.java 進(jìn)行修改:注釋掉 "Inheritable 的 @Inherited 注解"。
InheritableSon.java
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Inherited;
/**
- 自定義的Annotation。
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
//@Inherited
@interface Inheritable
{
}
@Inheritable
class InheritableFather
{
public InheritableFather() {
// InheritableBase是否具有 Inheritable Annotation
System.out.println("InheritableFather:"+InheritableFather.class.isAnnotationPresent(Inheritable.class));
}
}
/**
-
InheritableSon 類只是繼承于 InheritableFather,
*/
public class InheritableSon extends InheritableFather
{
public InheritableSon() {
super(); // 調(diào)用父類的構(gòu)造函數(shù)
// InheritableSon類是否具有 Inheritable Annotation
System.out.println("InheritableSon:"+InheritableSon.class.isAnnotationPresent(Inheritable.class));
}public static void main(String[] args)
{
InheritableSon is = new InheritableSon();
}
}
運(yùn)行結(jié)果:
<pre class="prettyprint prettyprinted" style="">InheritableFather:true InheritableSon:false</pre>
對(duì)比上面的兩個(gè)結(jié)果,我們發(fā)現(xiàn):當(dāng)注解 Inheritable 被 @Inherited 標(biāo)注時(shí),它具有繼承性。否則,沒(méi)有繼承性。
2.3) @SuppressWarnings
@SuppressWarnings 的定義如下:
<pre class="prettyprint prettyprinted" style="">@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { String[] value(); }</pre>
說(shuō)明:
(01) @interface -- 它的用來(lái)修飾 SuppressWarnings,意味著 SuppressWarnings 實(shí)現(xiàn)了 java.lang.annotation.Annotation 接口;即 SuppressWarnings 就是一個(gè)注解。
(02) @Retention(RetentionPolicy.SOURCE) -- 它的作用是指定 SuppressWarnings 的策略是 RetentionPolicy.SOURCE。這就意味著,SuppressWarnings 信息僅存在于編譯器處理期間,編譯器處理完之后 SuppressWarnings 就沒(méi)有作用了。
(03) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) -- 它的作用是指定 SuppressWarnings 的類型同時(shí)包括TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE。
- TYPE 意味著,它能標(biāo)注"類、接口(包括注釋類型)或枚舉聲明"。
- FIELD 意味著,它能標(biāo)注"字段聲明"。
- METHOD 意味著,它能標(biāo)注"方法"。
- PARAMETER 意味著,它能標(biāo)注"參數(shù)"。
- CONSTRUCTOR 意味著,它能標(biāo)注"構(gòu)造方法"。
- LOCAL_VARIABLE 意味著,它能標(biāo)注"局部變量"。
(04) String[] value(); 意味著,SuppressWarnings 能指定參數(shù)
(05) SuppressWarnings 的作用是,讓編譯器對(duì)"它所標(biāo)注的內(nèi)容"的某些警告保持靜默。例如,"@SuppressWarnings(value={"deprecation", "unchecked"})" 表示對(duì)"它所標(biāo)注的內(nèi)容"中的 "SuppressWarnings 不再建議使用警告"和"未檢查的轉(zhuǎn)換時(shí)的警告"保持沉默。示例如下:


SuppressWarningTest.java
import java.util.Date;
public class SuppressWarningTest {
//@SuppressWarnings(value={"deprecation"})
public static void doSomething(){
Date date = new Date(113, 8, 26);
System.out.println(date);
}
public static void main(String[] args) {
doSomething();
}
}
說(shuō)明:
(01) 左邊的圖中,沒(méi)有使用 @SuppressWarnings(value={"deprecation"}) , 而 Date 屬于 java 不再建議使用的類。因此,調(diào)用 Date 的 API 時(shí),會(huì)產(chǎn)生警告。而右邊的途中,使用了 @SuppressWarnings(value={"deprecation"})。因此,編譯器對(duì)"調(diào)用 Date 的 API 產(chǎn)生的警告"保持沉默。
補(bǔ)充:SuppressWarnings 常用的關(guān)鍵字的表格
<pre class="prettyprint prettyprinted" style="">deprecation -- 使用了不贊成使用的類或方法時(shí)的警告 unchecked -- 執(zhí)行了未檢查的轉(zhuǎn)換時(shí)的警告,例如當(dāng)使用集合時(shí)沒(méi)有用泛型 (Generics) 來(lái)指定集合保存的類型。 fallthrough -- 當(dāng) Switch 程序塊直接通往下一種情況而沒(méi)有 Break 時(shí)的警告。 path -- 在類路徑、源文件路徑等中有不存在的路徑時(shí)的警告。 serial -- 當(dāng)在可序列化的類上缺少 serialVersionUID 定義時(shí)的警告。 finally -- 任何 finally 子句不能正常完成時(shí)的警告。 all -- 關(guān)于以上所有情況的警告。</pre>
4、Annotation 的作用
Annotation 是一個(gè)輔助類,它在 Junit、Struts、Spring 等工具框架中被廣泛使用。
我們?cè)诰幊讨薪?jīng)常會(huì)使用到的 Annotation 作用有:
1)編譯檢查
Annotation 具有"讓編譯器進(jìn)行編譯檢查的作用"。
例如,@SuppressWarnings, @Deprecated 和 @Override 都具有編譯檢查作用。
(01) 關(guān)于 @SuppressWarnings 和 @Deprecated,已經(jīng)在"第3部分"中詳細(xì)介紹過(guò)了。這里就不再舉例說(shuō)明了。
(02) 若某個(gè)方法被 @Override 的標(biāo)注,則意味著該方法會(huì)覆蓋父類中的同名方法。如果有方法被 @Override 標(biāo)示,但父類中卻沒(méi)有"被 @Override 標(biāo)注"的同名方法,則編譯器會(huì)報(bào)錯(cuò)。示例如下:

OverrideTest.java
public class OverrideTest {
/**
* toString() 在java.lang.Object中定義;
* 因此,這里用 @Override 標(biāo)注是對(duì)的。
*/
@Override
public String toString(){
return "Override toString";
}
/**
* getString() 沒(méi)有在OverrideTest的任何父類中定義;
* 但是,這里卻用 @Override 標(biāo)注,因此會(huì)產(chǎn)生編譯錯(cuò)誤!
*/
@Override
public String getString(){
return "get toString";
}
public static void main(String[] args) {
}
}
上面是該程序在 eclipse 中的截圖。從中,我們可以發(fā)現(xiàn) "getString()" 函數(shù)會(huì)報(bào)錯(cuò)。這是因?yàn)?"getString() 被 @Override 所標(biāo)注,但在OverrideTest 的任何父類中都沒(méi)有定義 getString1() 函數(shù)"。
"將 getString() 上面的 @Override注釋掉",即可解決該錯(cuò)誤。
2) 在反射中使用 Annotation
在反射的 Class, Method, Field 等函數(shù)中,有許多于 Annotation 相關(guān)的接口。
這也意味著,我們可以在反射中解析并使用 Annotation。
AnnotationTest.java
import java.lang.annotation.Annotation;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Inherited;
import java.lang.reflect.Method;
/**
- Annotation在反射函數(shù)中的使用示例
*/
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String[] value() default "unknown";
}
/**
-
Person類。它會(huì)使用MyAnnotation注解。
*/
class Person {/**
- empty()方法同時(shí)被 "@Deprecated" 和 "@MyAnnotation(value={"a","b"})"所標(biāo)注
- (01) @Deprecated,意味著empty()方法,不再被建議使用
- (02) @MyAnnotation, 意味著empty() 方法對(duì)應(yīng)的MyAnnotation的value值是默認(rèn)值"unknown"
*/
@MyAnnotation
@Deprecated
public void empty(){
System.out.println("\nempty");
}
/**
- sombody() 被 @MyAnnotation(value={"girl","boy"}) 所標(biāo)注,
- @MyAnnotation(value={"girl","boy"}), 意味著MyAnnotation的value值是{"girl","boy"}
*/
@MyAnnotation(value={"girl","boy"})
public void somebody(String name, int age){
System.out.println("\nsomebody: "+name+", "+age);
}
}
public class AnnotationTest {
public static void main(String[] args) throws Exception {
// 新建Person
Person person = new Person();
// 獲取Person的Class實(shí)例
Class<Person> c = Person.class;
// 獲取 somebody() 方法的Method實(shí)例
Method mSomebody = c.getMethod("somebody", new Class[]{String.class, int.class});
// 執(zhí)行該方法
mSomebody.invoke(person, new Object[]{"lily", 18});
iteratorAnnotations(mSomebody);
// 獲取 somebody() 方法的Method實(shí)例
Method mEmpty = c.getMethod("empty", new Class[]{});
// 執(zhí)行該方法
mEmpty.invoke(person, new Object[]{});
iteratorAnnotations(mEmpty);
}
public static void iteratorAnnotations(Method method) {
// 判斷 somebody() 方法是否包含MyAnnotation注解
if(method.isAnnotationPresent(MyAnnotation.class)){
// 獲取該方法的MyAnnotation注解實(shí)例
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
// 獲取 myAnnotation的值,并打印出來(lái)
String[] values = myAnnotation.value();
for (String str:values)
System.out.printf(str+", ");
System.out.println();
}
// 獲取方法上的所有注解,并打印出來(lái)
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation : annotations){
System.out.println(annotation);
}
}
}
運(yùn)行結(jié)果:
<pre class="prettyprint prettyprinted" style="">somebody: lily, 18 girl, boy, @com.skywang.annotation.MyAnnotation(value=[girl, boy]) empty
unknown, @com.skywang.annotation.MyAnnotation(value=[unknown]) @java.lang.Deprecated()</pre>
3) 根據(jù) Annotation 生成幫助文檔
通過(guò)給 Annotation 注解加上 @Documented 標(biāo)簽,能使該 Annotation 標(biāo)簽出現(xiàn)在 javadoc 中。
4) 能夠幫忙查看查看代碼
通過(guò) @Override, @Deprecated 等,我們能很方便的了解程序的大致結(jié)構(gòu)。
另外,我們也可以通過(guò)自定義 Annotation 來(lái)實(shí)現(xiàn)一些功能。