关于注解:深入理解Java注解类型

9次阅读

共计 16296 个字符,预计需要花费 41 分钟才能阅读完成。

Java 注解是在 JDK5 时引入的新个性,鉴于目前大部分框架 (如 Spring) 都应用了注解简化代码并进步编码的效率,因而把握并深刻了解注解对于一个 Java 工程师是来说是很有必要的事。

了解 Java 注解

实际上 Java 注解与一般修饰符 (public、static、void 等) 的应用形式并没有多大区别,上面的例子是常见的注解:

public class AnnotationDemo {
    
    @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 注解是如何申明的:

@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 文件中可用,但会被 JVM 抛弃(该类型的注解信息会保留在源码里和 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

上述类型的数组

假使应用了其余数据类型,编译器将会丢出一个编译谬误,留神,申明注解元素时能够应用根本类型但不容许应用任何包装类型,同时还应该留神到注解也能够作为元素的类型,也就是嵌套注解,上面的代码演示了上述类型的应用过程:

@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 name()default "";

    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,简略案例如下

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface IntegerVaule{int value() default 0;
    String name() default "";}
public class QuicklyWay {@IntegerVaule(20)
    public int age;

    
    @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:对于以上所有状况的正告。

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

@Deprecatedclass 
A{public void A(){ }

    
    @Deprecated()
    public void B(){}
}

class B extends A{

    @Override 
    public void A() {super.A();
    }

    
    @SuppressWarnings({"uncheck","deprecation"})
    public void C(){} 
    
    @SuppressWarnings("uncheck")
    public void D(){}
}

后面咱们剖析了两种元注解,@Target 和 @Retention,除了这两种元注解,Java 还提供了另外两种元注解,@Documented 和 @Inherited,上面别离介绍:

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

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentA{}

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

@DocumentA
@DocumentB
public class DocumentDemo {public void A(){}}

应用 javadoc 命令生成文档:

如下:

能够发现应用 @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 接口,它次要用于示意目前正在 JVM 中运行的程序中已应用注解的元素,通过该接口提供的办法能够利用反射技术地读取注解的信息,如反射包的 Constructor 类、Field 类、Method 类、Package 类和 Class 类都实现了 AnnotatedElement 接口,它简要含意如下(更多具体介绍能够看 深刻了解 Java 类型信息 (Class 对象) 与反射机制):

Class:类的 Class 对象定义
Constructor:代表类的结构器定义
Field:代表类的成员变量定义
Method:代表类的办法定义
Package:代表类的包定义

上面是 AnnotatedElement 中相干的 API 办法,以上 5 个类都实现以下的办法

返回值 办法名称 阐明
A extends Annotation getAnnotation(Class annotationClass) 该元素如果存在指定类型的注解,则返回这些注解,否则返回 null。
Annotation[] getAnnotations() 返回此元素上存在的所有注解,包含从父类继承的
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 如果指定类型的注解存在于此元素上,则返回 true,否则返回 false。
Annotation[] getDeclaredAnnotations() 返回间接存在于此元素上的所有注解,留神,不包含父类的注解,调用者能够随便批改返回的数组;这不会对其余调用者返回的数组产生任何影响,没有则返回长度为 0 的数组

简略案例演示如下:

@DocumentA
class 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));

        
        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 "";
    
    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;
    
    boolean allowNull() default false;
    
    boolean unique() default false;}

/**
 * Created by wuzejian on 2017/5/18.
 * 数据库表 Member 对应实例类 bean
 */
@DBTable(name = "MEMBER")
public class Member {@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;

   
}

上述定义 4 个注解,别离是 @DBTable(用于类上)、@Constraints(用于字段上)、@SQLString(用于字段上)、@SQLString(用于字段上)并在 Member 类中应用这些注解,这些注解的作用的是用于帮忙注解处理器生成创立数据库表 MEMBER 的构建语句,在这里有点须要留神的是,咱们应用了嵌套注解 @Constraints,该注解次要用于判断字段是否为 null 或者字段是否惟一。必须分明意识到上述提供的注解生命周期必须为 @Retention(RetentionPolicy.RUNTIME),即运行时,这样才能够应用反射机制获取其信息。有了上述注解和应用,残余的就是编写上述的注解处理器了,后面咱们聊了很多注解,其处理器要么是 Java 本身已提供、要么是框架已提供的,咱们本人都没有波及到注解处理器的编写,但上述定义解决 SQL 的注解,其处理器必须由咱们本人编写了,如下

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(tableName.length() < 1)
      tableName = cl.getName().toUpperCase();
    List<String> columnDefs = new ArrayList<String>();
    
    for(Field field : cl.getDeclaredFields()) {
      String columnName = null;
      
      Annotation[] anns = field.getDeclaredAnnotations();
      if(anns.length < 1)
        continue; 

      
      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()));
      }
      
      if(anns[0] instanceof SQLString) {SQLString sString = (SQLString) anns[0];
        
        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 + ",");

    
    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 新退出的,它示意在同一个地位反复雷同的注解。在没有该注解前,个别是无奈在同一个类型上应用雷同的注解的

@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.
 */
@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/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 的话,依然无奈获取。上面通过代码来演示:

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;
        
        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 注解

public @interface FilterPath {String  value();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited 
@interface FilterPaths {FilterPath[] value();}

@FilterPath("/web/list")
@FilterPath("/web/getList")
class CC { }

class AA extends CC{public static void main(String[] args) {

        Class<?> clazz = AA.class;
        
        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) {T[] result = getDeclaredAnnotationsByType(annotationClass);if (result.length == 0 && this instanceof Class && 

 AnnotationType.getInstance(annotationClass).isInherited()) {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)。如下所示

class D<@Parameter T> { }

class Image implements @Rectangular Shape { }

new @Path String("/usr/bin")

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 
import java.lang.@NotNull String

这里次要阐明一下 TYPE_USE,类型注解用来反对在 Java 的程序中做强类型查看,配合第三方插件工具(如 Checker Framework),能够在编译期检测出 runtime error(如 UnsupportedOperationException、NullPointerException 异样),防止异样连续到运行期才发现,从而进步代码品质,这就是类型注解的次要作用。总之 Java 8 新减少了两个注解的元素类型 ElementType.TYPE_USE 和 ElementType.TYPE_PARAMETER,通过它们,咱们能够把注解利用到各种新场合中。

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

非原创!!
摘自https://www.cnblogs.com/tuanz…
正文完
 0