天天看點

關于java注解(Annotation)了解Java注解基本文法注解與反射機制運作時注解處理器Java 8中注解增強

本部落格轉載自:https://blog.csdn.net/javazejian/article/details/71860633?utm_source=copy

java注解是在JDK5時引入的新特性,鑒于目前大部分架構(如Spring)都使用了注解簡化代碼并提高編碼的效率,是以掌握并深入了解注解對于一個Java工程師是來說是很有必要的事。本篇我們将通過以下幾個角度來分析注解的相關知識點

  • 了解Java注解
  • 基本文法
    • 聲明注解與元注解
    • 注解元素及其資料類型
    • 編譯器對預設值的限制
    • 注解不支援繼承
    • 快捷方式
    • Java内置注解與其它元注解
  • 注解與反射機制
  • 運作時注解處理器
  • Java 8中注解增強
    • 元注解Repeatable
    • 新增的兩種ElementType

了解Java注解

實際上Java注解與普通修飾符(public、static、void等)的使用方式并沒有多大差別,下面的例子是常見的注解:

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提供的元注解,所謂元注解就是标記其他注解的注解,下面分别介紹

  • @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值時,則此注解可以用于任何元素之上,多個值使用{}包含并用逗号隔開,如下:
    @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内置注解與其它元注解

接着看看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指令生成文檔:
    [email protected] annotationdemo$ javadoc DocumentDemo.java DocumentA.java DocumentB.java 
               
    如下:
    關于java注解(Annotation)了解Java注解基本文法注解與反射機制運作時注解處理器Java 8中注解增強
    可以發現使用@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?

Java 8中注解增強

元注解@Repeatable

元注解@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;
}
           

新增的兩種ElementType

在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 [email protected] String //非法,不能标注import
           

這裡主要說明一下TYPE_USE,類型注解用來支援在Java的程式中做強類型檢查,配合第三方插件工具(如Checker Framework),可以在編譯期檢測出runtime error(如UnsupportedOperationException、NullPointerException異常),避免異常延續到運作期才發現,進而提高代碼品質,這就是類型注解的主要作用。總之Java 8 新增加了兩個注解的元素類型ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER ,通過它們,我們可以把注解應用到各種新場合中。