java註解是在JDK5時引入的新特性,鑑於目前大部分框架(如Spring)都使用了註解簡化代碼並提升編碼的效率,所以掌握並深刻理解註解對於一個Java工程師是來講是頗有必要的事。java
實際上Java註解與普通修飾符(public、static、void等)的使用方式並無多大區別,下面的例子是常見的註解:web
public class AnnotationDemo { //@Test註解修飾方法A @Test public static void A(){ System.out.println("Test....."); } //一個方法上能夠擁有多個不一樣的註解 @Deprecated @SuppressWarnings("uncheck") public static void B(){ } }
經過在方法上使用@Test註解後,在運行該方法時,測試框架會自動識別該方法並單獨調用,@Test其實是一種標記註解,起標記做用,運行時告訴測試框架該方法爲測試方法。而對於@Deprecated和@SuppressWarnings(「uncheck」),則是Java自己內置的註解,在代碼中,能夠常常看見它們,但這並非一件好事,畢竟當方法或是類上面有@Deprecated註解時,說明該方法或是類都已通過期不建議再用,@SuppressWarnings 則表示忽略指定警告,好比@SuppressWarnings(「uncheck」),這就是註解的最簡單的使用方式,那麼下面咱們就來看看註解定義的基本語法數據庫
咱們先來看看前面的Test註解是如何聲明的:數組
//聲明Test註解 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test { }
咱們使用了@interface
聲明瞭Test註解,並使用@Target
註解傳入ElementType.METHOD
參數來標明@Test只能用於方法上,@Retention(RetentionPolicy.RUNTIME)
則用來表示該註解生存期是運行時,從代碼上看註解的定義很像接口的定義,確實如此,畢竟在編譯後也會生成Test.class文件。對於@Target
和@Retention
是由Java提供的元註解,所謂元註解就是標記其餘註解的註解,下面分別介紹app
@Target 用來約束註解能夠應用的地方(如方法、類或字段),其中ElementType是枚舉類型,其定義以下,也表明可能的取值範圍框架
public enum ElementType { /**標明該註解能夠用於類、接口(包括註解類型)或enum聲明*/ TYPE, /** 標明該註解能夠用於字段(域)聲明,包括enum實例 */ FIELD, /** 標明該註解能夠用於方法聲明 */ METHOD, /** 標明該註解能夠用於參數聲明 */ PARAMETER, /** 標明註解能夠用於構造函數聲明 */ CONSTRUCTOR, /** 標明註解能夠用於局部變量聲明 */ LOCAL_VARIABLE, /** 標明註解能夠用於註解聲明(應用於另外一個註解上)*/ ANNOTATION_TYPE, /** 標明註解能夠用於包聲明 */ PACKAGE, /** * 標明註解能夠用於類型參數聲明(1.8新加入) * @since 1.8 */ TYPE_PARAMETER, /** * 類型使用聲明(1.8新加入) * @since 1.8 */ TYPE_USE }
請注意,當註解未指定Target值時,則此註解能夠用於任何元素之上,多個值使用{}包含並用逗號隔開,以下:ide
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
@Retention用來約束註解的生命週期,分別有三個值,源碼級別(source),類文件級別(class)或者運行時級別(runtime),其含有以下:函數
SOURCE:註解將被編譯器丟棄(該類型的註解信息只會保留在源碼裏,源碼通過編譯後,註解信息會被丟棄,不會保留在編譯好的class文件裏)工具
CLASS:註解在class文件中可用,但會被VM丟棄(該類型的註解信息會保留在源碼裏和class文件裏,在執行的時候,不會加載到虛擬機中),請注意,當註解未定義Retention值時,默認值是CLASS,如Java內置註解,@Override、@Deprecated、@SuppressWarnning等測試
RUNTIME:註解信息將在運行期(JVM)也保留,所以能夠經過反射機制讀取註解的信息(源碼、class文件和執行的時候都有註解的信息),如SpringMvc中的@Controller、@Autowired、@RequestMapping等。
經過上述對@Test註解的定義,咱們瞭解了註解定義的過程,因爲@Test內部沒有定義其餘元素,因此@Test也稱爲標記註解(marker annotation),但在自定義註解中,通常都會包含一些元素以表示某些值,方便處理器使用,這點在下面的例子將會看到:
/** * Created by wuzejian on 2017/5/18. * 對應數據表註解 */ @Target(ElementType.TYPE)//只能應用於類上 @Retention(RetentionPolicy.RUNTIME)//保存到運行時 public @interface DBTable { String name() default ""; }
上述定義一個名爲DBTable的註解,該用於主要用於數據庫表與Bean類的映射(稍後會有完整案例分析),與前面Test註解不一樣的是,咱們聲明一個String類型的name元素,其默認值爲空字符,可是必須注意到對應任何元素的聲明應採用方法的聲明方式,同時可選擇使用default提供默認值,@DBTable使用方式以下:
//在類上使用該註解 @DBTable(name = "MEMBER") public class Member { //....... }
關於註解支持的元素數據類型除了上述的String,還支持以下數據類型
全部基本類型(int,float,boolean,byte,double,char,long,short)
String
Class
enum
Annotation
上述類型的數組
假若使用了其餘數據類型,編譯器將會丟出一個編譯錯誤,注意,聲明註解元素時可使用基本類型但不容許使用任何包裝類型,同時還應該注意到註解也能夠做爲元素的類型,也就是嵌套註解,下面的代碼演示了上述類型的使用過程:
package com.zejian.annotationdemo; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by wuzejian on 2017/5/19. * 數據類型使用Demo */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Reference{ boolean next() default false; } public @interface AnnotationElementDemo { //枚舉類型 enum Status {FIXED,NORMAL}; //聲明枚舉 Status status() default Status.FIXED; //布爾類型 boolean showSupport() default false; //String類型 String name()default ""; //class類型 Class<?> testCase() default Void.class; //註解嵌套 Reference reference() default @Reference(next=true); //數組類型 long[] value(); }
編譯器對元素的默認值有些過度挑剔。首先,元素不能有不肯定的值。也就是說,元素必需要麼具備默認值,要麼在使用註解時提供元素的值。其次,對於非基本類型的元素,不管是在源代碼中聲明,仍是在註解接口中定義默認值,都不能以null做爲值,這就是限制,沒有什麼利用可言,但形成一個元素的存在或缺失狀態,由於每一個註解的聲明中,全部的元素都存在,而且都具備相應的值,爲了繞開這個限制,只能定義一些特殊的值,例如空字符串或負數,表示某個元素不存在。
註解是不支持繼承的,所以不能使用關鍵字extends來繼承某個@interface,但註解在編譯後,編譯器會自動繼承java.lang.annotation.Annotation接口,這裏咱們反編譯前面定義的DBTable註解
package com.zejian.annotationdemo; import java.lang.annotation.Annotation; //反編譯後的代碼 public interface DBTable extends Annotation { public abstract String name(); }
雖然反編譯後發現DBTable註解繼承了Annotation接口,請記住,即便Java的接口能夠實現多繼承,但定義註解時依然沒法使用extends關鍵字繼承@interface。
所謂的快捷方式就是註解中定義了名爲value的元素,而且在使用該註解時,若是該元素是惟一須要賦值的一個元素,那麼此時無需使用key=value的語法,而只需在括號內給出value元素所需的值便可。這能夠應用於任何合法類型的元素,記住,這限制了元素名必須爲value,簡單案例以下
package com.zejian.annotationdemo; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] */ //定義註解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface IntegerVaule{ int value() default 0; String name() default ""; } //使用註解 public class QuicklyWay { //當只想給value賦值時,可使用如下快捷方式 @IntegerVaule(20) public int age; //當name也須要賦值時必須採用key=value的方式賦值 @IntegerVaule(value = 10000,name = "MONEY") public int money; }
接着看看Java提供的內置註解,主要有3個,以下:
@Override:用於標明此方法覆蓋了父類的方法,源碼以下
@Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { }
@Deprecated:用於標明已通過時的方法或類,源碼以下,關於@Documented稍後分析:
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE}) public @interface Deprecated { }
@SuppressWarnnings:用於有選擇的關閉編譯器對類、方法、成員變量、變量初始化的警告,其實現源碼以下:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { String[] value(); }
其內部有一個String數組,主要接收值以下:
deprecation:使用了不同意使用的類或方法時的警告; unchecked:執行了未檢查的轉換時的警告,例如當使用集合時沒有用泛型 (Generics) 來指定集合保存的類型; fallthrough:當 Switch 程序塊直接通往下一種狀況而沒有 Break 時的警告; path:在類路徑、源文件路徑等中有不存在的路徑時的警告; serial:當在可序列化的類上缺乏 serialVersionUID 定義時的警告; finally:任何 finally 子句不能正常完成時的警告; all:關於以上全部狀況的警告。
這個三個註解比較簡單,看個簡單案例便可:
//註明該類已過期,不建議使用 @Deprecated class A{ public void A(){ } //註明該方法已過期,不建議使用 @Deprecated() public void B(){ } } class B extends A{ @Override //標明覆蓋父類A的A方法 public void A() { super.A(); } //去掉檢測警告 @SuppressWarnings({"uncheck","deprecation"}) public void C(){ } //去掉檢測警告 @SuppressWarnings("uncheck") public void D(){ } }
前面咱們分析了兩種元註解,@Target和@Retention,除了這兩種元註解,Java還提供了另外兩種元註解,@Documented和@Inherited,下面分別介紹:
@Documented 被修飾的註解會生成到javadoc中
/** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentA { } //沒有使用@Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentB { } //使用註解 @DocumentA @DocumentB public class DocumentDemo { public void A(){ } }
使用javadoc命令生成文檔:
zejian@zejiandeMBP annotationdemo$ javadoc DocumentDemo.java DocumentA.java DocumentB.java
以下:
能夠發現使用@Documented元註解定義的註解(@DocumentA)將會生成到javadoc中,而@DocumentB則沒有在doc文檔中出現,這就是元註解@Documented的做用。
@Inherited 可讓註解被繼承,但這並非真的繼承,只是經過使用@Inherited,可讓子類Class對象使用getAnnotations()獲取父類被@Inherited修飾的註解,以下:
@Inherited @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentA { } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentB { } @DocumentA class A{ } class B extends A{ } @DocumentB class C{ } class D extends C{ } //測試 public class DocumentDemo { public static void main(String... args){ A instanceA=new B(); System.out.println("已使用的@Inherited註解:"+Arrays.toString(instanceA.getClass().getAnnotations())); C instanceC = new D(); System.out.println("沒有使用的@Inherited註解:"+Arrays.toString(instanceC.getClass().getAnnotations())); } /** * 運行結果: 已使用的@Inherited註解:[@com.zejian.annotationdemo.DocumentA()] 沒有使用的@Inherited註解:[] */ }
前面通過反編譯後,咱們知道Java全部註解都繼承了Annotation接口,也就是說 Java使用Annotation接口表明註解元素,該接口是全部Annotation類型的父接口。同時爲了運行時能準確獲取到註解的相關信息,Java在java.lang.reflect 反射包下新增了AnnotatedElement接口,它主要用於表示目前正在 VM 中運行的程序中已使用註解的元素,經過該接口提供的方法能夠利用反射技術地讀取註解的信息,如反射包的Constructor類、Field類、Method類、Package類和Class類都實現了AnnotatedElement接口,它簡要含義以下(更多詳細介紹能夠看 深刻理解Java類型信息(Class對象)與反射機制):
Class:類的Class對象定義
Constructor:表明類的構造器定義
Field:表明類的成員變量定義
Method:表明類的方法定義
Package:表明類的包定義
下面是AnnotatedElement中相關的API方法,以上5個類都實現如下的方法
返回值 | 方法名稱 | 說明 |
---|---|---|
<A extends Annotation> |
getAnnotation(Class<A> annotationClass) |
該元素若是存在指定類型的註解,則返回這些註解,不然返回 null。 |
Annotation[] |
getAnnotations() |
返回此元素上存在的全部註解,包括從父類繼承的 |
boolean |
isAnnotationPresent(Class<? extends Annotation> annotationClass) |
若是指定類型的註解存在於此元素上,則返回 true,不然返回 false。 |
Annotation[] |
getDeclaredAnnotations() |
返回直接存在於此元素上的全部註解,注意,不包括父類的註解,調用者能夠隨意修改返回的數組;這不會對其餘調用者返回的數組產生任何影響,沒有則返回長度爲0的數組 |
簡單案例演示以下:
package com.zejian.annotationdemo; import java.lang.annotation.Annotation; import java.util.Arrays; /** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] */ @DocumentA class A{ } //繼承了A類 @DocumentB public class DocumentDemo extends A{ public static void main(String... args){ Class<?> clazz = DocumentDemo.class; //根據指定註解類型獲取該註解 DocumentA documentA=clazz.getAnnotation(DocumentA.class); System.out.println("A:"+documentA); //獲取該元素上的全部註解,包含從父類繼承 Annotation[] an= clazz.getAnnotations(); System.out.println("an:"+ Arrays.toString(an)); //獲取該元素上的全部註解,但不包含繼承! Annotation[] an2=clazz.getDeclaredAnnotations(); System.out.println("an2:"+ Arrays.toString(an2)); //判斷註解DocumentA是否在該元素上 boolean b=clazz.isAnnotationPresent(DocumentA.class); System.out.println("b:"+b); /** * 執行結果: A:@com.zejian.annotationdemo.DocumentA() an:[@com.zejian.annotationdemo.DocumentA(), @com.zejian.annotationdemo.DocumentB()] an2:@com.zejian.annotationdemo.DocumentB() b:true */ } }
瞭解完註解與反射的相關API後,如今經過一個實例(該例子是博主改編自《Tinking in Java》)來演示利用運行時註解來組裝數據庫SQL的構建語句的過程
/** * Created by wuzejian on 2017/5/18. * 表註解 */ @Target(ElementType.TYPE)//只能應用於類上 @Retention(RetentionPolicy.RUNTIME)//保存到運行時 public @interface DBTable { String name() default ""; } /** * Created by wuzejian on 2017/5/18. * 註解Integer類型的字段 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface SQLInteger { //該字段對應數據庫表列名 String name() default ""; //嵌套註解 Constraints constraint() default @Constraints; } /** * Created by wuzejian on 2017/5/18. * 註解String類型的字段 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface SQLString { //對應數據庫表的列名 String name() default ""; //列類型分配的長度,如varchar(30)的30 int value() default 0; Constraints constraint() default @Constraints; } /** * Created by wuzejian on 2017/5/18. * 約束註解 */ @Target(ElementType.FIELD)//只能應用在字段上 @Retention(RetentionPolicy.RUNTIME) public @interface Constraints { //判斷是否做爲主鍵約束 boolean primaryKey() default false; //判斷是否容許爲null boolean allowNull() default false; //判斷是否惟一 boolean unique() default false; } /** * Created by wuzejian on 2017/5/18. * 數據庫表Member對應實例類bean */ @DBTable(name = "MEMBER") public class Member { //主鍵ID @SQLString(name = "ID",value = 50, constraint = @Constraints(primaryKey = true)) private String id; @SQLString(name = "NAME" , value = 30) private String name; @SQLInteger(name = "AGE") private int age; @SQLString(name = "DESCRIPTION" ,value = 150 , constraint = @Constraints(allowNull = true)) private String description;//我的描述 //省略set get..... }
上述定義4個註解,分別是@DBTable(用於類上)、@Constraints(用於字段上)、 @SQLString(用於字段上)、@SQLString(用於字段上)並在Member類中使用這些註解,這些註解的做用的是用於幫助註解處理器生成建立數據庫表MEMBER的構建語句,在這裏有點須要注意的是,咱們使用了嵌套註解@Constraints,該註解主要用於判斷字段是否爲null或者字段是否惟一。必須清楚認識到上述提供的註解生命週期必須爲@Retention(RetentionPolicy.RUNTIME)
,即運行時,這樣纔可使用反射機制獲取其信息。有了上述註解和使用,剩餘的就是編寫上述的註解處理器了,前面咱們聊了不少註解,其處理器要麼是Java自身已提供、要麼是框架已提供的,咱們本身都沒有涉及到註解處理器的編寫,但上述定義處理SQL的註解,其處理器必須由咱們本身編寫了,以下
package com.zejian.annotationdemo; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * Created by zejian on 2017/5/13. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] * 運行時註解處理器,構造表建立語句 */ public class TableCreator { public static String createTableSql(String className) throws ClassNotFoundException { Class<?> cl = Class.forName(className); DBTable dbTable = cl.getAnnotation(DBTable.class); //若是沒有表註解,直接返回 if(dbTable == null) { System.out.println( "No DBTable annotations in class " + className); return null; } String tableName = dbTable.name(); // If the name is empty, use the Class name: if(tableName.length() < 1) tableName = cl.getName().toUpperCase(); List<String> columnDefs = new ArrayList<String>(); //經過Class類API獲取到全部成員字段 for(Field field : cl.getDeclaredFields()) { String columnName = null; //獲取字段上的註解 Annotation[] anns = field.getDeclaredAnnotations(); if(anns.length < 1) continue; // Not a db table column //判斷註解類型 if(anns[0] instanceof SQLInteger) { SQLInteger sInt = (SQLInteger) anns[0]; //獲取字段對應列名稱,若是沒有就是使用字段名稱替代 if(sInt.name().length() < 1) columnName = field.getName().toUpperCase(); else columnName = sInt.name(); //構建語句 columnDefs.add(columnName + " INT" + getConstraints(sInt.constraint())); } //判斷String類型 if(anns[0] instanceof SQLString) { SQLString sString = (SQLString) anns[0]; // Use field name if name not specified. if(sString.name().length() < 1) columnName = field.getName().toUpperCase(); else columnName = sString.name(); columnDefs.add(columnName + " VARCHAR(" + sString.value() + ")" + getConstraints(sString.constraint())); } } //數據庫表構建語句 StringBuilder createCommand = new StringBuilder( "CREATE TABLE " + tableName + "("); for(String columnDef : columnDefs) createCommand.append("\n " + columnDef + ","); // Remove trailing comma String tableCreate = createCommand.substring( 0, createCommand.length() - 1) + ");"; return tableCreate; } /** * 判斷該字段是否有其餘約束 * @param con * @return */ private static String getConstraints(Constraints con) { String constraints = ""; if(!con.allowNull()) constraints += " NOT NULL"; if(con.primaryKey()) constraints += " PRIMARY KEY"; if(con.unique()) constraints += " UNIQUE"; return constraints; } public static void main(String[] args) throws Exception { String[] arg={"com.zejian.annotationdemo.Member"}; for(String className : arg) { System.out.println("Table Creation SQL for " + className + " is :\n" + createTableSql(className)); } /** * 輸出結果: Table Creation SQL for com.zejian.annotationdemo.Member is : CREATE TABLE MEMBER( ID VARCHAR(50) NOT NULL PRIMARY KEY, NAME VARCHAR(30) NOT NULL, AGE INT NOT NULL, DESCRIPTION VARCHAR(150) ); */ } }
若是對反射比較熟悉的同窗,上述代碼就相對簡單了,咱們經過傳遞Member的全路徑後經過Class.forName()方法獲取到Member的class對象,而後利用Class對象中的方法獲取全部成員字段Field,最後利用field.getDeclaredAnnotations()
遍歷每一個Field上的註解再經過註解的類型判斷來構建建表的SQL語句。這即是利用註解結合反射來構建SQL語句的簡單的處理器模型,是否已回想起Hibernate?
元註解@Repeatable是JDK1.8新加入的,它表示在同一個位置重複相同的註解。在沒有該註解前,通常是沒法在同一個類型上使用相同的註解的
//Java8前沒法這樣使用 @FilterPath("/web/update") @FilterPath("/web/add") public class A {}
Java8前若是是想實現相似的功能,咱們須要在定義@FilterPath註解時定義一個數組元素接收多個值以下
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface FilterPath { String [] value(); } //使用 @FilterPath({"/update","/add"}) public class A { }
但在Java8新增了@Repeatable註解後就能夠採用以下的方式定義並使用了
package com.zejian.annotationdemo; import java.lang.annotation.*; /** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] */ //使用Java8新增@Repeatable原註解 @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Repeatable(FilterPaths.class)//參數指明接收的註解class public @interface FilterPath { String value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface FilterPaths { FilterPath[] value(); } //使用案例 @FilterPath("/web/update") @FilterPath("/web/add") @FilterPath("/web/delete") class AA{ }
咱們能夠簡單理解爲經過使用@Repeatable後,將使用@FilterPaths註解做爲接收同一個類型上重複註解的容器,而每一個@FilterPath則負責保存指定的路徑串。爲了處理上述的新增註解,Java8還在AnnotatedElement接口新增了getDeclaredAnnotationsByType() 和 getAnnotationsByType()兩個方法並在接口給出了默認實現,在指定@Repeatable的註解時,能夠經過這兩個方法獲取到註解相關信息。但請注意,舊版API中的getDeclaredAnnotation()和 getAnnotation()是不對@Repeatable註解的處理的(除非該註解沒有在同一個聲明上重複出現)。注意getDeclaredAnnotationsByType方法獲取到的註解不包括父類,其實當 getAnnotationsByType()方法調用時,其內部先執行了getDeclaredAnnotationsByType方法,只有當前類不存在指定註解時,getAnnotationsByType()纔會繼續從其父類尋找,但請注意若是@FilterPath和@FilterPaths沒有使用了@Inherited的話,仍然沒法獲取。下面經過代碼來演示:
/** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] */ //使用Java8新增@Repeatable原註解 @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Repeatable(FilterPaths.class) public @interface FilterPath { String value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface FilterPaths { FilterPath[] value(); } @FilterPath("/web/list") class CC { } //使用案例 @FilterPath("/web/update") @FilterPath("/web/add") @FilterPath("/web/delete") class AA extends CC{ public static void main(String[] args) { Class<?> clazz = AA.class; //經過getAnnotationsByType方法獲取全部重複註解 FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class); FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class); if (annotationsByType != null) { for (FilterPath filter : annotationsByType) { System.out.println("1:"+filter.value()); } } System.out.println("-----------------"); if (annotationsByType2 != null) { for (FilterPath filter : annotationsByType2) { System.out.println("2:"+filter.value()); } } System.out.println("使用getAnnotation的結果:"+clazz.getAnnotation(FilterPath.class)); /** * 執行結果(當前類擁有該註解FilterPath,則不會從CC父類尋找) 1:/web/update 1:/web/add 1:/web/delete ----------------- 2:/web/update 2:/web/add 2:/web/delete 使用getAnnotation的結果:null */ } }
從執行結果來看若是當前類擁有該註解@FilterPath,則getAnnotationsByType方法不會從CC父類尋找,下面看看另一種狀況,即AA類上沒有@FilterPath註解
/** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,請尊重原創] */ //使用Java8新增@Repeatable原註解 @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited //添加可繼承元註解 @Repeatable(FilterPaths.class) public @interface FilterPath { String value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited //添加可繼承元註解 @interface FilterPaths { FilterPath[] value(); } @FilterPath("/web/list") @FilterPath("/web/getList") class CC { } //AA上不使用@FilterPath註解,getAnnotationsByType將會從父類查詢 class AA extends CC{ public static void main(String[] args) { Class<?> clazz = AA.class; //經過getAnnotationsByType方法獲取全部重複註解 FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class); FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class); if (annotationsByType != null) { for (FilterPath filter : annotationsByType) { System.out.println("1:"+filter.value()); } } System.out.println("-----------------"); if (annotationsByType2 != null) { for (FilterPath filter : annotationsByType2) { System.out.println("2:"+filter.value()); } } System.out.println("使用getAnnotation的結果:"+clazz.getAnnotation(FilterPath.class)); /** * 執行結果(當前類沒有@FilterPath,getAnnotationsByType方法從CC父類尋找) 1:/web/list 1:/web/getList ----------------- 使用getAnnotation的結果:null */ } }
注意定義@FilterPath和@FilterPath時必須指明@Inherited,getAnnotationsByType方法不然依舊沒法從父類獲取@FilterPath註解,這是爲何呢,不妨看看getAnnotationsByType方法的實現源碼:
//接口默認實現方法 default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { //先調用getDeclaredAnnotationsByType方法 T[] result = getDeclaredAnnotationsByType(annotationClass); //判斷當前類獲取到的註解數組是否爲0 if (result.length == 0 && this instanceof Class && //判判定義註解上是否使用了@Inherited元註解 AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable //從父類獲取 Class<?> superClass = ((Class<?>) this).getSuperclass(); if (superClass != null) { result = superClass.getAnnotationsByType(annotationClass); } } return result; }
在Java8中 ElementType 新增兩個枚舉成員,TYPE_PARAMETER 和 TYPE_USE ,在Java8前註解只能標註在一個聲明(如字段、類、方法)上,Java8後,新增的TYPE_PARAMETER能夠用於標註類型參數,而TYPE_USE則能夠用於標註任意類型(不包括class)。以下所示
//TYPE_PARAMETER 標註在類型參數上 class D<@Parameter T> { } //TYPE_USE則能夠用於標註任意類型(不包括class) //用於父類或者接口 class Image implements @Rectangular Shape { } //用於構造函數 new @Path String("/usr/bin") //用於強制轉換和instanceof檢查,注意這些註解中用於外部工具,它們不會對類型轉換或者instanceof的檢查行爲帶來任何影響。 String path=(@Path String)input; if(input instanceof @Path String) //用於指定異常 public Person read() throws @Localized IOException. //用於通配符綁定 List<@ReadOnly ? extends Person> List<? extends @ReadOnly Person> @NotNull String.class //非法,不能標註class import java.lang.@NotNull String //非法,不能標註import
這裏主要說明一下TYPE_USE,類型註解用來支持在Java的程序中作強類型檢查,配合第三方插件工具(如Checker Framework),能夠在編譯期檢測出runtime error(如UnsupportedOperationException、NullPointerException異常),避免異常延續到運行期才發現,從而提升代碼質量,這就是類型註解的主要做用。總之Java 8 新增長了兩個註解的元素類型ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER ,經過它們,咱們能夠把註解應用到各類新場合中。