ava注解类型(@Annotation)

java注解是在JDK5时引入的新特性,鉴于目前大部分框架(如Spring)都使用了注解简化代码并提高编码的效率,因此掌握并深入理解注解对于一个Java工程师是来说是很有必要的事。本篇我们将通过以下几个角度来分析注解的相关知识点

  • 理解Java注解

  • 基本语法

    • 声明注解与元注解

    • 注解元素及其数据类型

    • 编译器对默认值的限制

    • 注解不支持继承

    • 快捷方式

    • Java内置注解与其它元注解

  • 注解与反射机制

  • 运行时注解处理器

  • Java 8中注解增强

    • 元注解Repeatable

    • 新增的两种ElementType

理解Java注解

注解本质是一个继承了Annotation的特殊接口,其具体实现类是Java运行时生成的动态代理类。而我们通过反射获取注解时,返回的是Java运行时生成的动态代理对象$Proxy1。通过代理对象调用自定义注解(接口)的方法,会最终调用AnnotationInvocationHandler的invoke方法。该方法会从memberValues这个Map中索引出对应的值。而memberValues的来源是Java常量池。

实际上Java注解与普通修饰符(public、static、void等)的使用方式并没有多大区别,下面的例子是常见的注解:

 
  1. public class AnnotationDemo {

  2.    

  3.    @Test

  4.    public static void A(){

  5.        System.out.println("Test.....");

  6.    }

  7.    @Deprecated

  8.    @SuppressWarnings("uncheck")

  9.    public static void B(){

  10.  
  11.    }

  12. }

通过在方法上使用@Test注解后,在运行该方法时,测试框架会自动识别该方法并单独调用,@Test实际上是一种标记注解,起标记作用,运行时告诉测试框架该方法为测试方法。而对于@Deprecated和@SuppressWarnings(“uncheck”),则是Java本身内置的注解,在代码中,可以经常看见它们,但这并不是一件好事,毕竟当方法或是类上面有@Deprecated注解时,说明该方法或是类都已经过期不建议再用,@SuppressWarnings 则表示忽略指定警告,比如@SuppressWarnings(“uncheck”),这就是注解的最简单的使用方式,那么下面我们就来看看注解定义的基本语法

基本语法

声明注解与元注解

我们先来看看前面的Test注解是如何声明的:

 
  1. @Target(ElementType.METHOD)

  2. @Retention(RetentionPolicy.RUNTIME)

  3. public @interface Test {}

我们使用了@interface声明了Test注解,并使用@Target注解传入ElementType.METHOD参数来标明@Test只能用于方法上,@Retention(RetentionPolicy.RUNTIME)则用来表示该注解生存期是运行时,从代码上看注解的定义很像接口的定义,确实如此,毕竟在编译后也会生成Test.class文件。对于@Target@Retention是由Java提供的元注解,所谓元注解就是标记其他注解的注解,下面分别介绍

  • @Target 用来约束注解可以应用的地方(如方法、类或字段),其中ElementType是枚举类型,其定义如下,也代表可能的取值范围

     

  •  
    1. public enum ElementType {

    2.    /**标明该注解可以用于类、接口(包括注解类型)或enum声明*/

    3.    TYPE,

    4.  
    5.    /** 标明该注解可以用于字段(域)声明,包括enum实例 */

    6.    FIELD,

    7.  
    8.    /** 标明该注解可以用于方法声明 */

    9.    METHOD,

    10.  
    11.    /** 标明该注解可以用于参数声明 */

    12.    PARAMETER,

    13.  
    14.    /** 标明注解可以用于构造函数声明 */

    15.    CONSTRUCTOR,

    16.  
    17.    /** 标明注解可以用于局部变量声明 */

    18.    LOCAL_VARIABLE,

    19.  
    20.    /** 标明注解可以用于注解声明(应用于另一个注解上)*/

    21.    ANNOTATION_TYPE,

    22.  
    23.    /** 标明注解可以用于包声明 */

    24.    PACKAGE,

    25.  
    26.    /**

    27.     * 标明注解可以用于类型参数声明(1.8新加入)

    28.     * @since 1.8

    29.     */

    30.    TYPE_PARAMETER,

    31.  
    32.    /**

    33.     * 类型使用声明(1.8新加入)

    34.     * @since 1.8

    35.     */

    36.    TYPE_USE

    37. }

  • 请注意,当注解未指定Target值时,则此注解可以用于任何元素之上,多个值使用{}包含并用逗号隔开,如下:

     

    @Retention用来约束注解的生命周期,分别有三个值,源码级别(source),类文件级别(class)或者运行时级别(runtime),其含有如下:
    
  • @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})

 

    • SOURCE:注解将被编译器丢弃(该类型的注解信息只会保留在源码里,源码经过编译后,注解信息会被丢弃,不会保留在编译好的class文件里)

    • CLASS:注解在class文件中可用,但会被VM丢弃(该类型的注解信息会保留在源码里和class文件里,在执行的时候,不会加载到虚拟机中),请注意,当注解未定义Retention值时,默认值是CLASS,如Java内置注解,@Override、@Deprecated、@SuppressWarnning等

    • RUNTIME:注解信息将在运行期(JVM)也保留,因此可以通过反射机制读取注解的信息(源码、class文件和执行的时候都有注解的信息),如SpringMvc中的@Controller、@Autowired、@RequestMapping等。

       

 

注解元素及其数据类型

通过上述对@Test注解的定义,我们了解了注解定义的过程,由于@Test内部没有定义其他元素,所以@Test也称为标记注解(marker annotation),但在自定义注解中,一般都会包含一些元素以表示某些值,方便处理器使用,这点在下面的例子将会看到:

 
  1. /**

  2. * Created by wuzejian on 2017/5/18.

  3. * 对应数据表注解

  4. */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DBTable {

  5.    String name() default "";

  6. }

上述定义一个名为DBTable的注解,该用于主要用于数据库表与Bean类的映射(稍后会有完整案例分析),与前面Test注解不同的是,我们声明一个String类型的name元素,其默认值为空字符,但是必须注意到对应任何元素的声明应采用方法的声明方式,同时可选择使用default提供默认值,@DBTable使用方式如下:

 
  1. @DBTable(name = "MEMBER")

  2. public class Member {

  3.    //

  4. }

关于注解支持的元素数据类型除了上述的String,还支持如下数据类型

  • 所有基本类型(int,float,boolean,byte,double,char,long,short)

  • String

  • Class

  • enum

  • Annotation

  • 上述类型的数组

倘若使用了其他数据类型,编译器将会丢出一个编译错误,注意,声明注解元素时可以使用基本类型但不允许使用任何包装类型,同时还应该注意到注解也可以作为元素的类型,也就是嵌套注解,下面的代码演示了上述类型的使用过程:

 
  1. @Target(ElementType.TYPE)

  2. @Retention(RetentionPolicy.RUNTIME)

  3. @interface Reference{

  4.    boolean next() default false;

  5. }public @interface AnnotationElementDemo {

  6.    

  7.    enum Status {FIXED,NORMAL};

  8.  
  9.    

  10.    Status status() default Status.FIXED;

  11.  
  12.    

  13.    boolean showSupport() default false;

  14.  
  15.    

  16.    String name()default "";

  17.  
  18.    

  19.    Class<?> testCase() default Void.class;

  20.  
  21.    

  22.    Reference reference() default @Reference(next=true);

  23.  
  24.    

  25.    long[] value();

  26. }

 

编译器对默认值的限制

编译器对元素的默认值有些过分挑剔。首先,元素不能有不确定的值。也就是说,元素必须要么具有默认值,要么在使用注解时提供元素的值。其次,对于非基本类型的元素,无论是在源代码中声明,还是在注解接口中定义默认值,都不能以null作为值,这就是限制,没有什么利用可言,但造成一个元素的存在或缺失状态,因为每个注解的声明中,所有的元素都存在,并且都具有相应的值,为了绕开这个限制,只能定义一些特殊的值,例如空字符串或负数,表示某个元素不存在。

 

注解不支持继承

注解是不支持继承的,因此不能使用关键字extends来继承某个@interface,但注解在编译后,编译器会自动继承java.lang.annotation.Annotation接口,这里我们反编译前面定义的DBTable注解

 
  1. package com.zejian.annotationdemo;

  2. import java.lang.annotation.Annotation;

  3. public interface DBTable extends Annotation{

  4.    public abstract String name();

  5. }

虽然反编译后发现DBTable注解继承了Annotation接口,请记住,即使Java的接口可以实现多继承,但定义注解时依然无法使用extends关键字继承@interface。

 

 

快捷方式

所谓的快捷方式就是注解中定义了名为value的元素,并且在使用该注解时,如果该元素是唯一需要赋值的一个元素,那么此时无需使用key=value的语法,而只需在括号内给出value元素所需的值即可。这可以应用于任何合法类型的元素,记住,这限制了元素名必须为value,简单案例如下

 
  1. @Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)

  2. @interface IntegerVaule{

  3.    int value() default 0;

  4.    String name() default "";

  5. }public class QuicklyWay {

  6.  
  7.    

  8.    @IntegerVaule(20)

  9.    public int age;

  10.  
  11.    

  12.    @IntegerVaule(value = 10000,name = "MONEY")

  13.    public int money;

  14.  
  15. }

 

Java内置注解与其它元注解

接着看看Java提供的内置注解,主要有3个,如下:

  • @Override:用于标明此方法覆盖了父类的方法,源码如下

 

 
  1. @Target(ElementType.METHOD)

  2. @Retention(RetentionPolicy.SOURCE)

  3. public @interface Override {}

  • @Deprecated:用于标明已经过时的方法或类,源码如下,关于@Documented稍后分析:

        

 
  1. @Documented@Retention(RetentionPolicy.RUNTIME)

  2. @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})

  3. public @interface Deprecated {}

  • @SuppressWarnnings:用于有选择的关闭编译器对类、方法、成员变量、变量初始化的警告,其实现源码如下:

     

  •  
    1. @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})

    2. @Retention(RetentionPolicy.SOURCE)

    3. public @interface SuppressWarnings {

    4.    String[] value();

    5. }

    其内部有一个String数组,主要接收值如下:

     

  •  
    1. deprecation:使用了不赞成使用的类或方法时的警告;

    2. unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型; 

    3. fallthrough:当 Switch 程序块直接通往下一种情况而没有 Break 时的警告;

    4. path:在类路径、源文件路径等中有不存在的路径时的警告; 

    5. serial:当在可序列化的类上缺少 serialVersionUID 定义时的警告; 

    6. finally:任何 finally 子句不能正常完成时的警告; 

    7. all:关于以上所有情况的警告。

这个三个注解比较简单,看个简单案例即可:

 
  1. @Deprecatedclass A{

  2.    public void A(){ }

  3.  
  4.    

  5.    @Deprecated()

  6.    public void B(){ }

  7. }

  8.  
  9. class B extends A{

  10.  
  11.    @Override 

  12.    public void A() {

  13.        super.A();

  14.    }

  15.  
  16.    

  17.    @SuppressWarnings({"uncheck","deprecation"})

  18.    public void C(){ } 

  19.    

  20.    @SuppressWarnings("uncheck")

  21.    public void D(){ }

  22. }

前面我们分析了两种元注解,@Target和@Retention,除了这两种元注解,Java还提供了另外两种元注解,@Documented和@Inherited,下面分别介绍:

  • @Documented  被修饰的注解会生成到javadoc中

     

  •  
    1. @Documented@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DocumentA {}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DocumentB {}@DocumentA@DocumentBpublic class DocumentDemo {

    2.    public void A(){

    3.    }

    4. }

    使用javadoc命令生成文档:

  • 如下: 

     

    可以发现使用@Documented元注解定义的注解(@DocumentA)将会生成到javadoc中,而@DocumentB则没有在doc文档中出现,这就是元注解@Documented的作用。

  • @Inherited 可以让注解被继承,但这并不是真的继承,只是通过使用@Inherited,可以让子类Class对象使用getAnnotations()获取父类被@Inherited修饰的注解,如下:

     

  •  
    1. @Inherited

    2. @Documented

    3. @Target(ElementType.TYPE)

    4. @Retention(RetentionPolicy.RUNTIME)

    5. public @interface DocumentA {}

    6. @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DocumentB {}

    7. @DocumentAclass A{ }

    8.  
    9. class B extends A{ }@DocumentBclass C{ }

    10.  
    11. class D extends C{ }public class DocumentDemo {

    12.  
    13.    public static void main(String... args){

    14.        A instanceA=new B();

    15.        System.out.println("已使用的@Inherited注解:"+Arrays.toString(instanceA.getClass().getAnnotations()));

    16.  
    17.        C instanceC = new D();

    18.  
    19.        System.out.println("没有使用的@Inherited注解:"+Arrays.toString(instanceC.getClass().getAnnotations()));

    20.    }

    21.  
    22.    /**

    23.     * 运行结果:

    24.     已使用的@Inherited注解:[@com.zejian.annotationdemo.DocumentA()]

    25.     没有使用的@Inherited注解:[]

    26.     */}

注解与反射机制

前面经过反编译后,我们知道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()返回此元素上存在的所有注解,包括从父类继承的
booleanisAnnotationPresent(Class<? extends Annotation>  annotationClass)如果指定类型的注解存在于此元素上,则返回 true,否则返回 false。
Annotation[]getDeclaredAnnotations()返回直接存在于此元素上的所有注解,注意,不包括父类的注解,调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响,没有则返回长度为0的数组

简单案例演示如下:

 
  1. @DocumentAclass A{ }@DocumentBpublic class DocumentDemo extends A{

  2.  
  3.    public static void main(String... args){

  4.  
  5.        Class<?> clazz = DocumentDemo.class;

  6.        

  7.        DocumentA documentA=clazz.getAnnotation(DocumentA.class);

  8.        System.out.println("A:"+documentA);

  9.  
  10.        

  11.        Annotation[] an= clazz.getAnnotations();

  12.        System.out.println("an:"+ Arrays.toString(an));

  13.        

  14.        Annotation[] an2=clazz.getDeclaredAnnotations();

  15.        System.out.println("an2:"+ Arrays.toString(an2));

  16.  
  17.        

  18.        boolean b=clazz.isAnnotationPresent(DocumentA.class);

  19.        System.out.println("b:"+b);

  20.  
  21.        /**

  22.         * 执行结果:

  23.         A:@com.zejian.annotationdemo.DocumentA()

  24.         an:[@com.zejian.annotationdemo.DocumentA(), @com.zejian.annotationdemo.DocumentB()]

  25.         an2:@com.zejian.annotationdemo.DocumentB()

  26.         b:true

  27.         */

  28.    }

  29. }

运行时注解处理器

了解完注解与反射的相关API后,现在通过一个实例(该例子是博主改编自《Tinking in Java》)来演示利用运行时注解来组装数据库SQL的构建语句的过程

 
  1. /**

  2. * Created by wuzejian on 2017/5/18.

  3. * 表注解

  4. */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DBTable {

  5.    String name() default "";

  6. }/**

  7. * Created by wuzejian on 2017/5/18.

  8. * 注解Integer类型的字段

  9. */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface SQLInteger {

  10.    

  11.    String name() default "";

  12.    

  13.    Constraints constraint() default @Constraints;

  14. }/**

  15. * Created by wuzejian on 2017/5/18.

  16. * 注解String类型的字段

  17. */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface SQLString {

  18.  
  19.    

  20.    String name() default "";

  21.  
  22.    

  23.    int value() default 0;

  24.  
  25.    Constraints constraint() default @Constraints;

  26. }/**

  27. * Created by wuzejian on 2017/5/18.

  28. * 约束注解

  29. */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Constraints {

  30.    

  31.    boolean primaryKey() default false;

  32.    

  33.    boolean allowNull() default false;

  34.    

  35.    boolean unique() default false;

  36. }/**

  37. * Created by wuzejian on 2017/5/18.

  38. * 数据库表Member对应实例类bean

  39. */@DBTable(name = "MEMBER")public class Member {

  40.    

  41.    @SQLString(name = "ID",value = 50, constraint = @Constraints(primaryKey = true))

  42.    private String id;

  43.  
  44.    @SQLString(name = "NAME" , value = 30)

  45.    private String name;

  46.  
  47.    @SQLInteger(name = "AGE")

  48.    private int age;

  49.  
  50.    @SQLString(name = "DESCRIPTION" ,value = 150 , constraint = @Constraints(allowNull = true))

  51.    private String description;

  52.  
  53.   

  54. }

上述定义4个注解,分别是@DBTable(用于类上)、@Constraints(用于字段上)、 @SQLString(用于字段上)、@SQLString(用于字段上)并在Member类中使用这些注解,这些注解的作用的是用于帮助注解处理器生成创建数据库表MEMBER的构建语句,在这里有点需要注意的是,我们使用了嵌套注解@Constraints,该注解主要用于判断字段是否为null或者字段是否唯一。必须清楚认识到上述提供的注解生命周期必须为@Retention(RetentionPolicy.RUNTIME),即运行时,这样才可以使用反射机制获取其信息。有了上述注解和使用,剩余的就是编写上述的注解处理器了,前面我们聊了很多注解,其处理器要么是Java自身已提供、要么是框架已提供的,我们自己都没有涉及到注解处理器的编写,但上述定义处理SQL的注解,其处理器必须由我们自己编写了,如下

 
  1. public class TableCreator {

  2.  
  3.  public static String createTableSql(String className) throws ClassNotFoundException {

  4.    Class<?> cl = Class.forName(className);

  5.    DBTable dbTable = cl.getAnnotation(DBTable.class);

  6.    

  7.    if(dbTable == null) {

  8.      System.out.println(

  9.              "No DBTable annotations in class " + className);

  10.      return null;

  11.    }

  12.    String tableName = dbTable.name();

  13.    

  14.    if(tableName.length() < 1)

  15.      tableName = cl.getName().toUpperCase();

  16.    List<String> columnDefs = new ArrayList<String>();

  17.    

  18.    for(Field field : cl.getDeclaredFields()) {

  19.      String columnName = null;

  20.      

  21.      Annotation[] anns = field.getDeclaredAnnotations();

  22.      if(anns.length < 1)

  23.        continue; 

  24.  
  25.      

  26.      if(anns[0] instanceof SQLInteger) {

  27.        SQLInteger sInt = (SQLInteger) anns[0];

  28.        

  29.        if(sInt.name().length() < 1)

  30.          columnName = field.getName().toUpperCase();

  31.        else

  32.          columnName = sInt.name();

  33.        

  34.        columnDefs.add(columnName + " INT" +

  35.                getConstraints(sInt.constraint()));

  36.      }

  37.      

  38.      if(anns[0] instanceof SQLString) {

  39.        SQLString sString = (SQLString) anns[0];

  40.        

  41.        if(sString.name().length() < 1)

  42.          columnName = field.getName().toUpperCase();

  43.        else

  44.          columnName = sString.name();

  45.        columnDefs.add(columnName + " VARCHAR(" +

  46.                sString.value() + ")" +

  47.                getConstraints(sString.constraint()));

  48.      }

  49.  
  50.  
  51.    }

  52.    

  53.    StringBuilder createCommand = new StringBuilder(

  54.            "CREATE TABLE " + tableName + "(");

  55.    for(String columnDef : columnDefs)

  56.      createCommand.append("\n    " + columnDef + ",");

  57.  
  58.    

  59.    String tableCreate = createCommand.substring(

  60.            0, createCommand.length() - 1) + ");";

  61.    return tableCreate;

  62.  }

  63.  
  64.  
  65.    /**

  66.     * 判断该字段是否有其他约束

  67.     * @param con

  68.     * @return

  69.     */

  70.  private static String getConstraints(Constraints con) {

  71.    String constraints = "";

  72.    if(!con.allowNull())

  73.      constraints += " NOT NULL";

  74.    if(con.primaryKey())

  75.      constraints += " PRIMARY KEY";

  76.    if(con.unique())

  77.      constraints += " UNIQUE";

  78.    return constraints;

  79.  }

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

  82.    String[] arg={"com.zejian.annotationdemo.Member"};

  83.    for(String className : arg) {

  84.      System.out.println("Table Creation SQL for " +

  85.              className + " is :\n" + createTableSql(className));

  86.    }

  87.  
  88.    /**

  89.     * 输出结果:

  90.     Table Creation SQL for com.zejian.annotationdemo.Member is :

  91.     CREATE TABLE MEMBER(

  92.     ID VARCHAR(50) NOT NULL PRIMARY KEY,

  93.     NAME VARCHAR(30) NOT NULL,

  94.     AGE INT NOT NULL,

  95.     DESCRIPTION VARCHAR(150)

  96.     );

  97.     */

  98.  }

  99. }

如果对反射比较熟悉的同学,上述代码就相对简单了,我们通过传递Member的全路径后通过Class.forName()方法获取到Member的class对象,然后利用Class对象中的方法获取所有成员字段Field,最后利用field.getDeclaredAnnotations()遍历每个Field上的注解再通过注解的类型判断来构建建表的SQL语句。这便是利用注解结合反射来构建SQL语句的简单的处理器模型,是否已回想起Hibernate?

Java 8中注解增强

 

元注解@Repeatable

元注解@Repeatable是JDK1.8新加入的,它表示在同一个位置重复相同的注解。在没有该注解前,一般是无法在同一个类型上使用相同的注解的

 
  1. @FilterPath("/web/update")

  2. @FilterPath("/web/add")

  3. public class A {}

Java8前如果是想实现类似的功能,我们需要在定义@FilterPath注解时定义一个数组元素接收多个值如下

 
  1. @Target(ElementType.TYPE)

  2. @Retention(RetentionPolicy.RUNTIME)

  3. public @interface FilterPath {

  4.    String [] value();

  5. }

  6. @FilterPath({"/update","/add"})

  7. public class A { }

但在Java8新增了@Repeatable注解后就可以采用如下的方式定义并使用了

 
  1. package com.zejian.annotationdemo;

  2. import java.lang.annotation.*;/**

  3. * Created by zejian on 2017/5/20.

  4. */

  5. @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})

  6. @Retention(RetentionPolicy.RUNTIME)

  7. @Repeatable(FilterPaths.class)

  8. public @interface FilterPath {

  9.    String  value();

  10. }

  11. @Target(ElementType.TYPE)

  12. @Retention(RetentionPolicy.RUNTIME)

  13. @interface FilterPaths {

  14.    FilterPath[] value();

  15. }

  16. @FilterPath("/web/update")

  17. @FilterPath("/web/add")

  18. @FilterPath("/web/delete")

  19. class AA{ }

我们可以简单理解为通过使用@Repeatable后,将使用@FilterPaths注解作为接收同一个类型上重复注解的容器,而每个@FilterPath则负责保存指定的路径串。为了处理上述的新增注解,Java8还在AnnotatedElement接口新增了getDeclaredAnnotationsByType() 和 getAnnotationsByType()两个方法并在接口给出了默认实现,在指定@Repeatable的注解时,可以通过这两个方法获取到注解相关信息。但请注意,旧版API中的getDeclaredAnnotation()和 getAnnotation()是不对@Repeatable注解的处理的(除非该注解没有在同一个声明上重复出现)。注意getDeclaredAnnotationsByType方法获取到的注解不包括父类,其实当 getAnnotationsByType()方法调用时,其内部先执行了getDeclaredAnnotationsByType方法,只有当前类不存在指定注解时,getAnnotationsByType()才会继续从其父类寻找,但请注意如果@FilterPath和@FilterPaths没有使用了@Inherited的话,仍然无法获取。下面通过代码来演示:

 
  1. public @interface FilterPath {

  2.    String  value();

  3. }@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@interface FilterPaths {

  4.    FilterPath[] value();

  5. }@FilterPath("/web/list")class CC { }@FilterPath("/web/update")@FilterPath("/web/add")@FilterPath("/web/delete")class AA extends CC{

  6.    public static void main(String[] args) {

  7.  
  8.        Class<?> clazz = AA.class;

  9.        

  10.        FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);

  11.        FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);

  12.        if (annotationsByType != null) {

  13.            for (FilterPath filter : annotationsByType) {

  14.                System.out.println("1:"+filter.value());

  15.            }

  16.        }

  17.  
  18.        System.out.println("-----------------");

  19.  
  20.        if (annotationsByType2 != null) {

  21.            for (FilterPath filter : annotationsByType2) {

  22.                System.out.println("2:"+filter.value());

  23.            }

  24.        }

  25.  
  26.  
  27.        System.out.println("使用getAnnotation的结果:"+clazz.getAnnotation(FilterPath.class));

  28.  
  29.  
  30.        /**

  31.         * 执行结果(当前类拥有该注解FilterPath,则不会从CC父类寻找)

  32.         1:/web/update

  33.         1:/web/add

  34.         1:/web/delete

  35.         -----------------

  36.         2:/web/update

  37.         2:/web/add

  38.         2:/web/delete

  39.         使用getAnnotation的结果:null

  40.         */

  41.    }

  42. }

从执行结果来看如果当前类拥有该注解@FilterPath,则getAnnotationsByType方法不会从CC父类寻找,下面看看另外一种情况,即AA类上没有@FilterPath注解

 
  1. public @interface FilterPath {

  2.  
  3.    String  value();

  4. }@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Inherited @interface FilterPaths {

  5.    FilterPath[] value();

  6. }@FilterPath("/web/list")@FilterPath("/web/getList")class CC { }class AA extends CC{

  7.    public static void main(String[] args) {

  8.  
  9.        Class<?> clazz = AA.class;

  10.        

  11.        FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);

  12.        FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);

  13.        if (annotationsByType != null) {

  14.            for (FilterPath filter : annotationsByType) {

  15.                System.out.println("1:"+filter.value());

  16.            }

  17.        }

  18.  
  19.        System.out.println("-----------------");

  20.  
  21.        if (annotationsByType2 != null) {

  22.            for (FilterPath filter : annotationsByType2) {

  23.                System.out.println("2:"+filter.value());

  24.            }

  25.        }

  26.  
  27.  
  28.        System.out.println("使用getAnnotation的结果:"+clazz.getAnnotation(FilterPath.class));

  29.  
  30.  
  31.        /**

  32.         * 执行结果(当前类没有@FilterPath,getAnnotationsByType方法从CC父类寻找)

  33.         1:/web/list

  34.         1:/web/getList

  35.         -----------------

  36.         使用getAnnotation的结果:null

  37.         */

  38.    }

  39. }

注意定义@FilterPath和@FilterPath时必须指明@Inherited,getAnnotationsByType方法否则依旧无法从父类获取@FilterPath注解,这是为什么呢,不妨看看getAnnotationsByType方法的实现源码:

 
  1. default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {

  2.  
  3. T[] result = getDeclaredAnnotationsByType(annotationClass);if (result.length == 0 && this instanceof Class && 

  4.  
  5. AnnotationType.getInstance(annotationClass).isInherited()) { 

  6.        

  7.       Class<?> superClass = ((Class<?>) this).getSuperclass();

  8.   if (superClass != null) {

  9.      result = superClass.getAnnotationsByType(annotationClass);

  10.       }

  11.   }

  12.  
  13.   return result;

  14. }

 

新增的两种ElementType

在Java8中 ElementType 新增两个枚举成员,TYPE_PARAMETER 和 TYPE_USE ,在Java8前注解只能标注在一个声明(如字段、类、方法)上,Java8后,新增的TYPE_PARAMETER可以用于标注类型参数,而TYPE_USE则可以用于标注任意类型(不包括class)。如下所示

 
  1. class D<@Parameter T> { }class Image implements @Rectangular Shape { }new @Path String("/usr/bin")

  2.  
  3.  
  4. String path=(@Path String)input;if(input instanceof @Path String)public Person read() throws @Localized IOException.List<@ReadOnly ? extends Person>List<? extends @ReadOnly Person>

  5.  
  6. @NotNull String.class 

  7. import java.lang.@NotNull String

这里主要说明一下TYPE_USE,类型注解用来支持在Java的程序中做强类型检查,配合第三方插件工具(如Checker Framework),可以在编译期检测出runtime error(如UnsupportedOperationException、NullPointerException异常),避免异常延续到运行期才发现,从而提高代码质量,这就是类型注解的主要作用。总之Java 8 新增加了两个注解的元素类型ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER ,通过它们,我们可以把注解应用到各种新场合中。

ok~,关于注解暂且聊到这,实际上还有一个大块的知识点没详细聊到,源码级注解处理器,这个话题博主打算后面另开一篇分析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值