1.什么是注解
用一個詞就可以描述注解,那就是元數據,即一種描述數據的數據。所以,可以說注解就是源代碼的元數據。比如,下面這段代碼:
1
2
3
4
|
@override public string tostring() { return "this is string representation of current object." ; } |
上面的代碼中,我重寫了tostring()方法并使用了@override注解。但是,即使我不使用@override注解標記代碼,程序也能夠正常執行。那么,該注解表示什么?這么寫有什么好處嗎?事實上,@override告訴編譯器這個方法是一個重寫方法(描述方法的元數據),如果父類中不存在該方法,編譯器便會報錯,提示該方法沒有重寫父類中的方法。如果我不小心拼寫錯誤,例如將tostring()寫成了tostrring(){double r},而且我也沒有使用@override注解,那程序依然能編譯運行。但運行結果會和我期望的大不相同。現在我們了解了什么是注解,并且使用注解有助于閱讀程序。
annotation是一種應用于類、方法、參數、變量、構造器及包聲明中的特殊修飾符。它是一種由jsr-175標準選擇用來描述元數據的一種工具。
2.為什么要使用注解
使用annotation之前(甚至在使用之后),xml被廣泛的應用于描述元數據。不知何時開始一些應用開發人員和架構師發現xml的維護越來越糟糕了。他們希望使用一些和代碼緊耦合的東西,而不是像xml那樣和代碼是松耦合的(在某些情況下甚至是完全分離的)代碼描述。
假如你想為應用設置很多的常量或參數,這種情況下,xml是一個很好的選擇,因為它不會同特定的代碼相連。如果你想把某個方法聲明為服務,那么使用annotation會更好一些,因為這種情況下需要注解和方法緊密耦合起來,開發人員也必須認識到這點。
另一個很重要的因素是annotation定義了一種標準的描述元數據的方式。在這之前,開發人員通常使用他們自己的方式定義元數據。例如,使用標記interfaces,注釋,transient關鍵字等等。每個程序員按照自己的方式定義元數據,而不像annotation這種標準的方式。
3.基本語法
編寫annotation非常簡單,可以將annotation的定義同接口的定義進行比較。我們來看兩個例子:一個是標準的注解@override,另一個是用戶自定義注解@todo。
1
2
3
4
|
@target (elementtype.method) @retention (retentionpolicy.source) public @interface override { } |
對于@override注釋你可能有些疑問,它什么都沒做,那它是如何檢查在父類中有一個同名的函數呢。當然,不要驚訝,我是逗你玩的。@override注解的定義不僅僅只有這么一點代碼。這部分內容很重要,我不得不再次重復:annotations僅僅是元數據,和業務邏輯無關。理解起來有點困難,但就是這樣。如果annotations不包含業務邏輯,那么必須有人來實現這些邏輯。元數據的用戶來做這個事情。annotations僅僅提供它定義的屬性(類/方法/包/域)的信息。annotations的用戶(同樣是一些代碼)來讀取這些信息并實現必要的邏輯。
當我們使用java的標注annotations(例如@override)時,jvm就是一個用戶,它在字節碼層面工作。到這里,應用開發人員還不能控制也不能使用自定義的注解。因此,我們講解一下如何編寫自定義的annotations。
我們來逐個講述編寫自定義annotations的要點。上面的例子中,你看到一些注解應用在注解上。
3.1 四種基本元注解
j2se5.0版本在 java.lang.annotation提供了四種元注解,專門注解其他的注解:
@documented –注解是否將包含在javadoc中
@retention –什么時候使用該注解
@target? –注解用于什么地方
@inherited – 是否允許子類繼承該注解
@documented–一個簡單的annotations標記注解,表示是否將注解信息添加在java文檔中。
@retention– 定義該注解的生命周期。
retentionpolicy.source – 在編譯階段丟棄。這些注解在編譯結束之后就不再有任何意義,所以它們不會寫入字節碼。@override, @suppresswarnings都屬于這類注解。
retentionpolicy.class – 在類加載的時候丟棄。在字節碼文件的處理中有用。注解默認使用這種方式。
retentionpolicy.runtime– 始終不會丟棄,運行期也保留該注解,因此可以使用反射機制讀取該注解的信息。我們自定義的注解通常使用這種方式。
@target – 表示該注解用于什么地方。如果不明確指出,該注解可以放在任何地方。以下是一些可用的參數。需要說明的是:屬性的注解是兼容的,如果你想給7個屬性都添加注解,僅僅排除一個屬性,那么你需要在定義target包含所有的屬性。
elementtype.type:用于描述類、接口或enum聲明
elementtype.field:用于描述實例變量
elementtype.method
elementtype.parameter
elementtype.constructor
elementtype.local_variable
elementtype.annotation_type 另一個注釋
elementtype.package 用于記錄java文件的package信息
@inherited – 定義該注釋和子類的關系
那么,注解的內部到底是如何定義的呢?annotations只支持基本類型、string及枚舉類型。注釋中所有的屬性被定義成方法,并允許提供默認值。
1
2
3
4
5
6
7
8
9
|
@target (elementtype.method) @retention (retentionpolicy.runtime) @interface todo { public enum priority {low, medium, high} public enum status {started, not_started} string author() default "yash" ; priority priority() default priority.low; status status() default status.not_started; } |
下面的例子演示了如何使用上面的注解。
1
2
3
4
5
|
@todo (priority = todo.priority.medium, author = "yashwant" , status = todo.status.started) public void incompletemethod1() { //some business logic is written //but it's not complete yet } |
如果注解中只有一個屬性,可以直接命名為“value”,使用時無需再標明屬性名。
1
2
3
4
5
6
|
@interface author{ string value(); } @author ( "yashwant" ) public void somemethod() { } |
3.2 重復注解
在java8以前,同一個程序元素前只能使用一個相同類型的annotation;如果需要在同一個元素前使用多個類型相同的annotation,則必須使用annotation“容器”。
下面先介紹這種“容器”,
首先定義個mytag注解:
1
2
3
4
5
6
7
8
9
|
//指定注解保留到運行時 @retention (retentionpolicy.runtime) //指定注解可以修飾類、接口、枚舉 @target (elementtype.type) @interface mytag { string name() default "測試" ; int age() default 20 ; } |
然后再定義mytag注解的容器注解:
1
2
3
4
5
6
7
8
|
//指定注解保留到運行時 @retention (retentionpolicy.runtime) //指定注解可以修飾類、接口、枚舉 @target (elementtype.type) @interface mytags { mytag[] value(); } |
然后就可以按照如下的方式來使用注解了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@mytags ({ @mytag (name= "測試1" ,age= 21 ), @mytag (name= "測試2" ,age= 22 ) }) public class test { public static void main(string[] args) { //通過反射解析注解 class testclass= test. class ; //獲得mytags注解 mytags mytagsannotation= (mytags) testclass.getannotation(mytags. class ); //獲得添加到里面的mytag注解 mytag[] mytags=mytagsannotation.value(); for (mytag mytag : mytags) { system.out.println(string.format( "name:%1$s,age:%2$d" ,mytag.name(),mytag.age())); } } } |
打印:
name:測試1,age:21
name:測試2,age:22
java8為上面這種繁瑣的語法提供了糖語法,在java8中新增加了@repeatable元注解,只需要在mytag注解上添加上元注解@repeatable(mytags.class)。
觀察可以發現,@repeatable依然需要依賴容器注解,所以依然可以按照如下的方式來使用:
1
2
3
4
|
@mytags ({ @mytag (name= "測試1" ,age= 21 ), @mytag (name= "測試2" ,age= 22 ) }) |
又因為mytag是重復注解,所以還可以像如下這樣使用:
1
2
|
@mytag (name= "測試1" ,age= 21 ) @mytag (name= "測試2" ,age= 22 ) |
這里需要注意,重復注解只是一種簡便寫法,多個重復注解其實會被作為“容器”注解的value成員變量的數組元素。例如上面重復的mytag注解會被作為@mytags注解的value成員變量的數組元素處理。
4.使用注解
現在我們已經知道了可以通過使用@retention注解來指定注解的生存周期,注解的生存周期有三種,分別為:retentionpolicy.source,retentionpolicy.class,retentionpolicy.runtime,這三個值分別表示注解的生存周期為源代碼,字節碼,運行時中。
接下來介紹注解在不同階段中的處理:
4.1 運行時處理的注解
其實在上面的案例中,已經展示了如何使用反射獲取注解的數據。如果要在程序運行時處理注解,那么必須將注解的聲明周期聲明為: @retention(retentionpolicy.runtime) 。
由于注解本身是不包含任何業務邏輯的,在運行時中,我們就可以通過反射來實現具體的邏輯,
先定義一個debug注解:
1
2
3
4
5
6
7
8
|
//指定注解保留到運行時 @retention (retentionpolicy.runtime) //指定該注解只能用于方法 @target (elementtype.method) @interface debug { boolean value() default false ; } |
接下來將該注解和具體的業務邏輯關聯起來:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
public class debugtest { public static void main(string[] args) { class debugtestclass = debugtest. class ; //獲得所有的方法 method[] methods = debugtestclass.getmethods(); for (method method : methods) { method.setaccessible( true ); //禁用安全機制 if (method.isannotationpresent(debug. class )) { //檢查是否使用了debug注解 debug debug = method.getannotation(debug. class ); //獲得注解實例 string name = method.getname(); //獲得方法名稱 if (debug.value()) { system.out.println( "method:" + name + " should debug" ); } else { system.out.println( "method:" + name + " should't debug" ); } } } } @debug ( false ) public void testmethod1() { } @debug ( true ) public void testmethod2() { } @debug ( true ) public void testmethod3() { } @debug ( false ) public void testmethod4() { } @debug ( true ) public void testmethod5() { } } |
4.2 編譯時處理的注解
若是編譯時需要處理的注解,那么可以把注解的聲明周期聲明為: @retention(retentionpolicy.source) 。
在這里需要先介紹一下apt,api(annotation processing tool)是一種注解處理工具,他對源代碼進行檢測,并找出源代碼所包含的annotation信息,然后針對annotation信息進行額外的處理。使用apt工具處理annotation時可以根據源文件中的annotation生成額外的源文件和其他的文件(文件的具體內容由annotation處理器的編寫者決定),apt還會將編譯生成的源代碼文件和原來的源文件一起生成class文件。
使用apt的主要目的是為了簡化開發者的工作量,因為apt可以在編譯程序源代碼的同時生成一些附屬文件(比如源文件、類文件、程序發布描述文件等),這些附屬文件的內容也都與源代碼相關。換句話說,使用apt可以代替傳統的對代碼信息和附屬文件的維護工具。
java提供的javac.exe工具有一個-processor選項,該選項可指定一個annotation處理器,如果在編譯java源文件時指定了該annotation處理器,那么這個annotation處理器將會在編譯時提取并處理java源文件中的annotaion.
每一個annoataion處理器都需要實現javax.annotataion.processor包下的processor接口,不過實現該接口必須實現該接口下的所有的方法,因此通常會采用繼承abstractprocessor的方式來實現annotation的處理器。一個annotation處理器可以處理一個或多個annotaion注解。
在hibernate中,如果使用非注解的方式,那么每寫一個java bean類文件,還必須額外地維護一個hibernate映射文件(名為*.hbm.xml的文件),下面將使用apt來簡化這步操作。
為了示范使用apt根據源文件中的注解來生成額外的文件,下面定義3種注解。
標識持久化類的@persistent 注解:
1
2
3
4
5
6
7
8
9
|
//指定該注解可以修飾類,接口,枚舉 @target (elementtype.type) //指定該注解保留到編譯時 @retention (retentionpolicy.source) //指定該注解可以被顯示在文檔中(通過javadoc生成文檔,便可以在被該注解修飾的元素上看到該注解信息) @documented public @interface persistent { string table(); } |
標識屬性的@id 注解:
1
2
3
4
5
6
7
8
9
10
11
|
//指定該注解只能修飾字段 @target (elementtype.field) //指定該注解保留到編譯時 @retention (retentionpolicy.source) //指定該注解可以被顯示在文檔中(通過javadoc生成文檔,便可以在被該注解修飾的元素上看到該注解信息) @documented public @interface id { string column(); string type(); string generator(); } |
標識屬性的@property 注解
1
2
3
4
5
6
7
8
9
10
|
//指定該注解只能修飾字段 @target (elementtype.field) //指定該注解保留到編譯時 @retention (retentionpolicy.source) //指定該注解可以被顯示在文檔中(通過javadoc生成文檔,便可以在被該注解修飾的元素上看到該注解信息) @documented public @interface property { string column(); string type(); } |
在有了三個annotation后,我們定義一個簡單的java bean類person.java.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@persistent (table= "personinfo" ) public class person { @id (column= "person_id" ,type= "integer" ,generator= "identity" ) private int id; @property (column= "person_name" ,type= "string" ) private string name; @property (column= "person_age" ,type= "integer" ) private int age; public person(){} public person( int id,string name, int age) { this .id=id; this .name=name; this .age=age; } //所有屬性的setter和getter..... } |
接下來寫一個api工具,該api工具是根據java類中的注解來生成一個hibernate 映射文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import java.io.file; import java.io.fileoutputstream; import java.io.printstream; import java.util.set; import javax.annotation.processing.abstractprocessor; import javax.annotation.processing.roundenvironment; import javax.annotation.processing.supportedannotationtypes; import javax.annotation.processing.supportedsourceversion; import javax.lang.model.sourceversion; import javax.lang.model.element.element; import javax.lang.model.element.elementkind; import javax.lang.model.element.name; import javax.lang.model.element.typeelement; //指定該注解支持java平臺的最新版本為6.0 @supportedsourceversion (sourceversion.release_6) //指定可以處理persistent,id,property注解 @supportedannotationtypes ({ "persistent" , "id" , "property" }) public class hibernateannotationprocessor extends abstractprocessor{ @override public boolean process(set<? extends typeelement> annotations, roundenvironment roundenv) { //定義文件輸出流,用于生成額外的文件 printstream ps= null ; try { for (element t:roundenv.getelementsannotatedwith(persistent. class )){ //獲取正在處理的類名稱 name classname=t.getsimplename(); //獲得類定義前的@persistent annotation persistent per= t.getannotation(persistent. class ); //創建文件輸出流 ps= new printstream( new fileoutputstream( new file(classname+ ".hbm.xml" ))); //執行輸出 ps.println( "<?xml version=\"1.0\"?>" ); ps.println( "<!doctype hibernate-mapping public \"-//hibernate/hibernate mapping dtd 3.0//en\"" ); ps.println( "\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">" ); ps.println( "<hibernate-mapping>" ); ps.println( "<class name=\"" +classname+ "\" table=\"" +per.table()+ "\" >" ); for (element f:t.getenclosedelements()) { //只處理成員變量上的annotation if (f.getkind()==elementkind.field) { //獲取成員變量定義前的@id annotation id id=f.getannotation(id. class ); //但@id注解存在時,輸出<id ../>元素 if (id!= null ) { ps.println( "<id name=\"" +f.getsimplename()+ "\" " + "column=\"" +id.column()+ "\" " + "type=\"" +id.type()+ "\">" ); ps.println( "<generator class=\"" +id.generator()+ "\" />" ); ps.println( "</id>" ); continue ; } //獲取成員變量前的@property annotation property p=f.getannotation(property. class ); if (p!= null ) { ps.println( "<property name=\"" +f.getsimplename()+ "\" " + "column=\"" +p.column()+ "\" " + "type=\"" +p.type()+ "\" />" ); continue ; } } } ps.println( "</class>" ); ps.println( "</hibernate-mapping>" ); } } catch (exception e) { e.printstacktrace(); } finally { if (ps!= null ) ps.close(); } return true ; } } |
在編譯完hibernateannotationprocessor.java后執行如下的命令:
1
|
javac -processor hibernateannotationprocessor person.java |
就可以看到在該路徑下多了一個person.cfg.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
|
<?xml version= "1.0" ?> <!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> < class name= "person" table= "personinfo" > <id name= "id" column= "person_id" type= "integer" > <generator class = "identity" /> </id> <property name= "name" column= "person_name" type= "string" /> <property name= "age" column= "person_age" type= "integer" /> </ class > </hibernate-mapping> |