天天看點

java annotation 開發_Java Annotation入門

一、為什麼使用Annotation:

在JAVA應用中,我們常遇到一些需要使用模版代碼。例如,為了編寫一個JAX-RPC web service,我們必須提供一對接口和實作作為模版代碼。如果使用annotation對遠端通路的方法代碼進行修飾的話,這個模版就能夠使用工具自動生成。

外,一些API需要使用與程式代碼同時維護的附屬檔案。例如,JavaBeans需要一個BeanInfo

Class與一個Bean同時使用/維護,而EJB則同樣需要一個部署描述符。此時在程式中使用annotation來維護這些附屬檔案的資訊将十分便利

而且減少了錯誤。

二、Annotation工作方式:

在5.0

版之前的Java平台已經具有了一些ad hoc

annotation機制。比如,使用transient修飾符來辨別一個成員變量在序列化子系統中應被忽略。而@deprecated這個

javadoc tag也是一個ad hoc

annotation用來說明一個方法已過時。從Java5.0版釋出以來,5.0平台提供了一個正式的annotation功能:允許開發者定義、使用

自己的annoatation類型。此功能由一個定義annotation類型的文法和一個描述annotation聲明的文法,讀取annotaion

的API,一個使用annotation修飾的class檔案,一個annotation處理工具(apt)組成。

annotation并不直接影響代碼語義,但是它能夠工作的方式被看作類似程式的工具或者類庫,它會反過來對正在運作的程式語義有所影響。annotation可以從源檔案、class檔案或者以在運作時反射的多種方式被讀取。

當然annotation在某種程度上使javadoc tag更加完整。一般情況下,如果這個标記對java文檔産生影響或者用于生成java文檔的話,它應該作為一個javadoc tag;否則将作為一個annotation。

三、Annotation使用方法:

1。類型聲明方式:

通常,應用程式并不是必須定義annotation類型,但是定義annotation類型并非難事。Annotation類型聲明于一般的接口聲明極為類似,差別隻在于它在interface關鍵字前面使用“@”符号。

annotation

類型的每個方法聲明定義了一個annotation類型成員,但方法聲明不必有參數或者異常聲明;方法傳回值的類型被限制在以下的範圍:

primitives、String、Class、enums、annotation和前面類型的數組;方法可以有預設值。

下面是一個簡單的annotation類型聲明:

清單1:

public @interface RequestForEnhancement {

int    id();

String synopsis();

String engineer() default "[unassigned]";

String date();    default "[unimplemented]";

}

代碼中隻定義了一個annotation類型RequestForEnhancement。

2。修飾方法的annotation聲明方式:

annotation

是一種修飾符,能夠如其它修飾符(如public、static、final)一般使用。習慣用法是annotaions用在其它的修飾符前面。

annotations由“@+annotation類型+帶有括号的成員-值清單”組成。這些成員的值必須是編譯時常量(即在運作時不變)。

A:下面是一個使用了RequestForEnhancement annotation的方法聲明:

清單2:

@RequestForEnhancement(

id       = 2868724,

synopsis = "Enable time-travel",

engineer = "Mr. Peabody",

date     = "4/1/3007"

)

public static void travelThroughTime(Date destination) { ... }

B:當聲明一個沒有成員的annotation類型聲明時,可使用以下方式:

清單3:

public @interface Preliminary { }

作為上面沒有成員的annotation類型聲明的簡寫方式:

清單4:

@Preliminary public class TimeTravel { ... }

C:如果在annotations中隻有唯一一個成員,則該成員應命名為value:

清單5:

public @interface Copyright {

String value();

}

更為友善的是對于具有唯一成員且成員名為value的annotation(如上文),在其使用時可以忽略掉成員名和指派号(=):

清單6:

@Copyright("2002 Yoyodyne Propulsion Systems")

public class OscillationOverthruster { ... }

3。一個使用執行個體:

結合上面所講的,我們在這裡建立一個簡單的基于annotation測試架構。首先我們需要一個annotation類型來表示某個方法是一個應該被測試工具運作的測試方法。

清單7:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface Test { }

值得注意的是annotaion類型聲明是可以标注自己的,這樣的annotation被稱為“meta-annotations”。

上面的代碼中,@Retention(RetentionPolicy.RUNTIME)這個meta-annotation表示了此類型的

annotation将被虛拟機保留使其能夠在運作時通過反射被讀取。而@Target(ElementType.METHOD)表示此類型的

annotation隻能用于修飾方法聲明。

下面是一個簡單的程式,其中部分方法被上面的annotation所标注:

清單8:

public class Foo {

@Test public static void m1() { }

public static void m2() { }

@Test public static void m3() {

throw new RuntimeException("Boom");

}

public static void m4() { }

@Test public static void m5() { }

public static void m6() { }

@Test public static void m7() {

throw new RuntimeException("Crash");

}

public static void m8() { }

}

Here is the testing tool:

import java.lang.reflect.*;

public class RunTests {

public static void main(String[] args) throws Exception {

int passed = 0, failed = 0;

for (Method m : Class.forName(args[0]).getMethods()) {

if (m.isAnnotationPresent(Test.class)) {

try {

m.invoke(null);

passed++;

} catch (Throwable ex) {

System.out.printf("Test %s failed: %s %n", m, ex.getCause());

failed++;

}

}

}

System.out.printf("Passed: %d, Failed %d%n", passed, failed);

}

}

個程式從指令行參數中取出類名,并且周遊此類的所有方法,嘗試調用其中被上面的測試annotation類型标注過的方法。在此過程中為了找出哪些方法被

annotation類型标注過,需要使用反射的方式執行此查詢。如果在調用方法時抛出異常,此方法被認為已經失敗,并列印一個失敗報告。最後,列印運作

通過/失敗的方法數量。

下面文字表示了如何運作這個基于annotation的測試工具:

清單9:

$ java RunTests Foo

Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom

Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash

Passed: 2, Failed 2

四、Annotation分類:

根據annotation的使用方法和用途主要分為以下幾類:

1。内建Annotation——Java5.0版在java文法中經常用到的内建Annotation:

@Deprecated用于修飾已經過時的方法;

@Override用于修飾此方法覆寫了父類的方法(而非重載);

@SuppressWarnings用于通知java編譯器禁止特定的編譯警告。

下面代碼展示了内建Annotation類型的用法:

清單10:

package com.bjinfotech.practice.annotation;

import java.util.List;

public class UsingBuiltInAnnotation {

//食物類

class Food{}

//幹草類

class Hay extends Food{}

//動物類

class Animal{

Food getFood(){

return null;

}

//使用Annotation聲明Deprecated方法

@Deprecated

void deprecatedMethod(){

}

}

//馬類-繼承動物類

class Horse extends Animal{

//使用Annotation聲明覆寫方法

@Override

Hay getFood(){

return new Hay();

}

//使用Annotation聲明禁止警告

@SuppressWarnings({"deprecation","unchecked"})

void callDeprecatedMethod(List horseGroup){

Animal an=new Animal();

an.deprecatedMethod();

horseGroup.add(an);

}

}

}

2。開發者自定義Annotation:由開發者自定義Annotation類型。

下面是一個使用annotation進行方法測試的sample:

AnnotationDefineForTestFunction類型定義如下:

清單11:

package com.bjinfotech.practice.annotation;

import java.lang.annotation.*;

//加載在VM中,在運作時進行映射

@Retention(RetentionPolicy.RUNTIME)

//限定此annotation隻能标示方法

@Target(ElementType.METHOD)

public @interface AnnotationDefineForTestFunction{}

測試annotation的代碼如下:

清單12:

package com.bjinfotech.practice.annotation;

import java.lang.reflect.*;

public class UsingAnnotation {

@AnnotationDefineForTestFunction public static void method01(){}

public static void method02(){}

@AnnotationDefineForTestFunction public static void method03(){

throw new RuntimeException("method03");

}

public static void method04(){

throw new RuntimeException("method04");

}

public static void main(String[] argv) throws Exception{

int passed = 0, failed = 0;

//被檢測的類名

String className="com.bjinfotech.practice.annotation.UsingAnnotation";

//逐個檢查此類的方法,當其方法使用annotation聲明時調用此方法

for (Method m : Class.forName(className).getMethods()) {

if (m.isAnnotationPresent(AnnotationDefineForTestFunction.class)) {

try {

m.invoke(null);

passed++;

} catch (Throwable ex) {

System.out.printf("測試 %s 失敗: %s %n", m, ex.getCause());

failed++;

}

}

}

System.out.printf("測試結果: 通過: %d, 失敗: %d%n", passed, failed);

}

}

3。使用第三方開發的Annotation類型

這也是開發人員所常常用到的一種方式。比如我們在使用Hibernate3.0時就可以利用Annotation生成資料表映射配置檔案,而不必使用Xdoclet。