Java Annotation 机制源码分析与使用

1 Annotationhtml

1.1 Annotation 概念及做用java

     1.  概念数组

  An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.[3]安全

  可以添加到 Java 源代码的语法元数据。类、方法、变量、参数、包均可以被注解,可用来将信息元数据与程序元素进行关联。oracle

  更直观的理解,它提供了一种安全的相似注释的机制,用来将任何的信息或元数据(metadata)与程序元素(类、方法、成员变量等)进行关联。less

     2.  定义    ide

   Annotation经过以下的方式进行定义函数

public @interface Override {
}

  其中的@interface是一个关键字,这个关键字声明隐含了一个信息:它是继承了java.lang.annotation.Annotation接口,并不是声明了一个interface。在设计annotations的时候必须把一个类型定义为@interface,而不能用class或interface关键字。定义的详细内容参考[1.2.3]自定义Annotation一节。ui

  3.  做用this

  Annotation的引入是为了从Java语言层面上,为Java源代码提供元数据的支持

    (1).   标记,用于告诉编译器一些信息

    Marker Annotation:该Annotation没有参数输入,更多相似于标识一个东西,相似于Java语言中的java.io.Serialable之类的接口,并没有须要实现的方法。

    (2).   编译时动态处理,如动态生成代码

    (3).   运行时动态处理,如获得注解信息

1.2  Annotation 分类

1.2.1    标准 Annotation

      1.     @Override

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

   2.     @Deprecated

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}

   3.    @SuppressWarnings

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    String[] value();
}

  标准Annotation是指Java自带的几个Annotation,上面三个分别表示重写函数,函数已经被禁止使用,忽略某项Warning

1.2.2    元 Annotation

 元Annotation是指用来定义Annotation的Annotation

     1.   @Retention

 @Retention表示Annotation做用范围和保留时间,可选值SOURCE(源码时),CLASS(编译时),RUNTIME(运行时),默认为 CLASS,值为 SOURCE 大都为Mark   Annotation,这类Annotation 大都用来校验,好比Override, SuppressWarnings

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    RetentionPolicy value();
}
public enum RetentionPolicy {
    /* Annotations are to be discarded by the compiler. */
    SOURCE,
    /* Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior. */
    CLASS,
    /* Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     * @see java.lang.reflect.AnnotatedElement */
    RUNTIME
}

   2.     @Target

  @Target 表示Annotation能够用来修饰哪些程序元素,如 TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER 等,未标注则表示可修饰全部

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}
public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    /** Field declaration (includes enum constants) */
    FIELD,
    /** Method declaration */
    METHOD,
    /** Parameter declaration */
    PARAMETER,
    /** Constructor declaration */
    CONSTRUCTOR,
    /** Local variable declaration */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** Package declaration */
    PACKAGE
}

   3.     @Inherited[4][5]

  @Inherited 表示父类Annotation能够被子类继承

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

  @Inherited标识某个被标注的类型是被继承的。使用了@Inherited修饰的annotation类型被用于一个class之时,则这个annotation将被用于该class的相应子类。

  注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。

   当@Inherited annotation类型标注的annotation的Retention是RetentionPolicy.RUNTIME,则反射API加强了这种继承性。若是咱们使用java.lang.reflect去查询一个  @Inherited annotation类型的annotation时,反射代码检查将展开工做:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。

  就是说, 查看查找@Inherited过的Annotation之时,须要反复的向上查找,方才能够。

     4.     @Documented

  @Documented所修饰的Annotation连同自定义Annotation所修饰的元素一同保存到Javadoc文档中

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

 1.2.3    自定义Annotation

  自定义Annotation表示本身根据须要定义的Annotation,定义时须要用到上面的元Annotation。这里只是一种分类而已,也能够根据做用域分为源码时、编译时、运行时 Annotation。

  下面经过自定义Annotation MethodInfo,以实例来具体介绍自定义Annotation的使用。

   1.   自定义Annotation定义

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface MethodInfo {
     String author() default "trinea@gmail.com";
     String date();
     int version() default 1;
}

  MethodInfo Annotation定义部分:

    (1)   经过@interface 定义,注解名即为自定义注解名

    (2)   注解配置参数名为注解类的方法名,且:

      a)   全部方法没有方法体,方法名即为属性名,没有参数没有修饰符,实际只容许 public & abstract 修饰符,默认为 public ,不容许抛异常

      b)  方法返回值只能是基本类型,String, Class, annotation, enumeration 或者是他们的一维数组,返回类型即为属性类型

      c)  若只有一个默认属性,可直接用 value() 函数。一个属性都没有表示该 Annotation 为 Mark Annotation

      d)  能够加 default 表示默认值,null不能做为成员默认值

    2.      自定义Annotation调用

public class App {
    @MethodInfo( author =“xiaotian”, date="2014/02/14", version=2)
    public String getAppName() {
        return "trinea";
    }
}

这里是调用自定义Annotation--MethodInfo的示例,MethodInfo Annotation 做用为给方法添加相关信息,包括 author、date、version

    3.   运行时Annotation解析

    (1).   Annotation解析API

  运行时Annotation指@Retention为RUNTIME的Annotation,可手动调用下面经常使用 API 解析。

public interface AnnotatedElement {
    /* Returns true if an annotation for the specified type
     * is present on this element, else false.  This method
     * is designed primarily for convenient access to marker annotations.*/
   boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);

    /* Returns this element's annotation for the specified type if
     * such an annotation is present, else null */
   <T extends Annotation> T getAnnotation(Class<T> annotationClass);

    /* Returns all annotations present on this element.  (Returns an array
     * of length zero if this element has no annotations.)  The caller of
     * this method is free to modify the returned array; it will have no
     * effect on the arrays returned to other callers */
    Annotation[] getAnnotations();

    /* Returns all annotations that are directly present on this
     * element.  Unlike the other methods in this interface, this method
     * ignores inherited annotations.  (Returns an array of length zero if
     * no annotations are directly present on this element.)  The caller of
     * this method is free to modify the returned array; it will have no
     * effect on the arrays returned to other callers */
    Annotation[] getDeclaredAnnotations();

}

  其中Constructor,Field,Method都继承类class AccessibleObject implements AnnotatedElement;可经过以下接口来解析annotation:

  • element.getAnnotation(AnnotationName.class):

  表示获得element某个 AnnotationName的信息,由于一个 Target 能够被多个 Annotation 修饰

  •  element.getAnnotations( ) :

  则表示获得element全部Annotations

  • element.isAnnotationPresent(AnnotationName.class):

  表示该元素是否被某个 AnnotationNam修饰

  (2).    App解析实例分析

public static void main(String[] args) {
    try {
        Class cls = Class.forName("java.test.annotation.App");
        for (Method method : cls.getMethods()) {
            MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);
            if (methodInfo != null) {
                System.out.println("method name:" + method.getName());
                System.out.println("method author:" + methodInfo.author());
                System.out.println("method version:" + methodInfo.version());
                System.out.println("method date:" + methodInfo.date());
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

  以上解析代码以MethodInfo Annotation为例,利用 Target(这里是 Method)getAnnotation函数获得Annotation信息,而后就能够调用Annotation的方法获得响应属性值

  4.      编译时Annotation解析

    (1).     编译时Annotation解析过程

  编译时Annotation指@Retention为CLASS 的Annotation,由apt(Annotation Processing Tool) 解析自动解析。

  须要作的

      a)   自定义类集成自AbstractProcessor

      b)   重写其中的 process 函数

      实际是 apt(Annotation Processing Tool) 在编译时自动查找全部继承自 AbstractProcessor 的类,而后调用他们的 process 方法去处理

    (2).     解析示例

  假设以前自定义的MethodInfo的@Retention为CLASS,

@SupportedAnnotationTypes({ " java.test.annotation.MethodInfo" })
public class MethodInfoProcessor extends AbstractProcessor {
     @Override
    public boolean process(Set<?extends TypeElement> annotations, RoundEnvironment env) {
        HashMap<String, String> map = new HashMap<String, String>();
        for (TypeElement te : annotations) {
            for (Element element : env.getElementsAnnotatedWith(te)) {
                MethodInfo methodInfo = element.getAnnotation(MethodInfo.class);
                map.put(element.getEnclosingElement().toString(), methodInfo.author());
            }
        }
        return false;
    }
}

  SupportedAnnotationTypes表示这个Processor要处理的Annotation 名字。process函数中参数annotations表示待处理的 Annotations,参数 env 表示当前或是以前的运行环境, process函数返回值表示这组annotations是否被这个 Processor 接受,若是接受后续子的 rocessor不会再对这个Annotations 进行处理。

  

参考

[1].    The Java™ Tutorials : http://docs.oracle.com/javase/tutorial/java/annotations/

[2].   APT: Compile-Time Annotation Processing with Java

http://www.javalobby.org/java/forums/t17876.html

[3].   Java annotation : http://en.wikipedia.org/wiki/Java_annotation

[4].     Java中@Inherited注解的运用: http://xiangdefei.iteye.com/blog/1044199

[5].   Annotation Inheritance Examples: http://www.jroller.com/alessiopace/entry/annotation_inheritance_examples

相关文章
相关标签/搜索