Java Annotation Mechanism source code analysis and use

Source: Internet
Author: User
Tags deprecated

1 Annotation

The concept and function of 1.1 Annotation

1. Concept

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

Syntax metadata that can be added to the Java source code. Classes, methods, variables, parameters, and packages can be annotated, and can be used to correlate information metadata with program elements.

A more intuitive understanding, it provides a secure, comment-like mechanism for associating any information or metadata (metadata) with program elements (classes, methods, member variables, and so on).

2. Definition

Annotation is defined in the following way

Public @interface Override {}

The @interface is a keyword, and the keyword declaration implies a message that it inherits the Java.lang.annotation.Annotation interface and does not declare a interface. When designing a annotations, you must define a type as @interface, not a class or interface keyword. Define the detailed content reference [1.2.3] custom Annotation section.

3. Role

Annotation was introduced to provide metadata support for Java source code from the Java language level

(1). Tag, used to tell the compiler some information

Marker Annotation: The Annotation has no parameter input, more like an interface that identifies something like a java.io.Serialable in the Java language, and there is no way to implement it.

(2). Compile-time dynamic processing, such as dynamically generated code

(3). Run-time dynamic processing, such as getting annotation information

1.2 Annotation classification

1.2.1 Standard 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 ();}

Standard annotation refers to the Java comes with a few annotation, the above three represents the overriding function, the function has been forbidden to use, ignoring an item warning

1.2. $2 Annotation

Meta annotation refers to the annotation used to define annotation

1. @Retention

The @Retention represents the Annotation scope and retention time, the optional value source (source code), class (Compile time), runtime (runtime), the default is CLASS, and the value of most of the source is Mark Annotation, This type of annotation is mostly used for calibration, such as override, Suppresswarnings

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface Retention {    retentionpolicy value ();} public enum Retentionpolicy {/    * Annotations    is to is discarded by the compiler. */SOURCE,/    * Annotations ar E to being recorded in the class file by the compiler * and need not being retained by the     VM at run time.  This     is the default * behavior. */    CLASS,/    * Annotations is 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 means that annotation can be used to modify which program elements, such as TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER, and so on, are not labeled to modify all

@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,    /** F Ield 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 means that the parent class annotation can inherit from the quilt class

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) Public @interface inherited {}

@Inherited identifies that a labeled type is inherited. When a annotation type that uses the @inherited modifier is used for a class, the annotation is used for the corresponding subclass of the class.

Note: @Inherited the annotation type is inherited by subclasses of the class being labeled. The annotation class does not inherit from the interface it implements, and the method does not inherit annotation from the method it overloads.

The reflection API enhances this inheritance when the retention of the @inherited annotation type callout annotation is retentionpolicy.runtime. If we use Java.lang.reflect to query a annotation of a @Inherited annotation type, the reflection code check will work: Examine the class and its parent class until the specified annotation type is found. or reach the top level of the class inheritance structure.

That is, to look for @inherited annotation, you need to look up repeatedly, just can.

4. @Documented

@Documented decorated annotation are saved to the Javadoc document together with the elements modified by the custom annotation

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface documented {}

1.2.3 Custom annotation

custom annotation represents the annotation that you define as needed, and the meta-annotation above is used to define it. This is only a classification, but also according to the scope of the source code, compile time, run-time Annotation.

The use of custom annotation is described in detail below through custom annotation MethodInfo.

   1. Custom Annotation Definitions

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.method) @Inheritedpublic @interface MethodInfo {     String author () default "[email protected]";     String date ();     int version () default 1;}

MethodInfo Annotation Definition section:

(1) By @interface definition, the annotation name is the custom annotation name

(2) The annotation configuration parameter is named the method name of the annotation class, and:

A) All methods have no method body, the method name is the property name, no parameter has no modifier, only the public & abstract modifier is allowed, the default is public, and no throw exception is allowed

b) The method return value can only be a primitive type, String, Class, annotation, enumeration, or their one-dimensional array, the return type is the property type

c) If there is only one default property, you can use the value () function directly. An attribute does not indicate that the Annotation is a Mark Annotation

d) The default value can be added as null cannot be a member default

2. custom Annotation calls

public class App {    @MethodInfo (author = "Xiaotian", date= "2014/02/14", version=2) public    String Getappname () { C6/>return "Trinea";    }}

Here is an example of invoking a custom annotation--methodinfo, MethodInfo Annotation function to add related information to a method, including author, date, version

3. Run- time Annotation parsing

(1). Annotation parsing API

Run-time annotation refers to @retention as runtime annotation, can be manually called the following common API parsing.

 Public Interfaceannotatedelement {/*Returns True if the annotation for the specified type * are present on this element, else false. This method * was designed primarily for convenient access to marker annotations.*/   BooleanIsannotationpresent (class<?extendsAnnotation>Annotationclass); /*Returns This element ' s annotation for the specified type if * Such a annotation is present, else null*/<textendsAnnotation> T getannotation (class<t>Annotationclass); /*Returns all annotations present on the This element.  (Returns an array * of length zero if the This element has no annotations.) The caller of * This method was free to modify the returned array; It'll has no * effect on the arrays returned to other callers*/annotation[] Getannotations (); /*Returns all annotations is directly present on the This * element.  Unlike the other methods-interface, this method * ignores inherited annotations.  (Returns an array of length zero if * No annotations is directly present on the This element.) The caller of * This method was free to modify the returned array; It'll has no * effect on the arrays returned to other callers*/annotation[] Getdeclaredannotations ();}

Where constructor,field,method inherit class AccessibleObject implements Annotatedelement, the following interfaces can be used to parse annotation:

    • Element.getannotation (Annotationname.class):

Represents the information for a annotationname of element, because a Target can be modified by more than one Annotation

    • Element.getannotations ():

It means that all annotations of the element are

    • Element.isannotationpresent (Annotationname.class):

Indicates whether the element is decorated by a Annotationnam

(2). App parsing Example Analysis

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 ();    }}

The above parsing code takes MethodInfo annotation as an example, uses the Target (here is Method) getannotation function to get annotation information, then can call annotation method to get the response property value

4. Compile- time Annotation parsing

(1). Compile-time Annotation parsing process

Compile-time Annotation refers to @retention as Class Annotation, which is parsed automatically by apt (Annotation processing Tool).

Need to do

A) custom class integration from Abstractprocessor

b) rewrite the process function within it

In fact , APT (Annotation processing Tool) automatically finds all classes that inherit from Abstractprocessor at compile time, and then calls their process method to handle

(2). Parsing Examples

Assuming that the @retention of the previously customized MethodInfo is 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 method Info = Element.getannotation (methodinfo.class);                Map.put (Element.getenclosingelement (). toString (), Methodinfo.author ());            }        }        return false;    }}

Supportedannotationtypes represents the annotation name to be handled by this processor. The parameter Annotations in the Process function represents the Annotations to be processed, and the parameter env represents the current or previous run environment, and the process function return value indicates whether this set of Annotations is accepted by this Processor. If the rocessor of the subsequent child is accepted, the annotations will not be processed again.

Reference

[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]. Application of @inherited annotations in Java: http://xiangdefei.iteye.com/blog/1044199

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

Java Annotation Mechanism source code analysis and use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.