In-depth understanding of Java: Annotations (Annotation) Getting Started with custom annotations

Source: Internet
Author: User

  To learn more about annotations, we must be able to define our own annotations and use annotations to define our own annotations before we have to understand the syntax of the meta-annotations and related definition annotations that Java provides us.

Meta-Annotations:

The role of meta annotations is to be responsible for annotating other annotations. Java5.0 defines 4 standard meta-annotation types, which are used to provide descriptions of other annotation types. Java5.0 defined meta-annotations:
[Email protected],
[Email protected],
[Email protected],
[Email protected]
These types and the classes they support can be found in the Java.lang.annotation package. Let's take a look at the function of each meta-annotation and the instructions for using the corresponding sub-parameters.

  @Target:

@Target illustrates the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Target can be more clearly decorated by using target in the declaration of the annotation type.

  Function: Used to describe the scope of use of annotations (i.e., where the annotations described can be used)

 The values (ElementType) are:

1.CONSTRUCTOR: Used to describe the constructor
2.FIELD: Used to describe the domain
3.local_variable: Used to describe local variables
4.METHOD: Used to describe the method
5.PACKAGE: Used to describe the package
6.PARAMETER: Used to describe parameters
7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations

Usage examples:

@Target (elementtype.type) public @interface Table {    /**     * Datasheet name annotation, the default value is class name     * @return     */Public    String tableName () default "ClassName";} @Target (Elementtype.field) public @interface Nodbcolumn {}

Note Table can be used for annotation classes, interfaces (including annotation types), or enum declarations, and annotation nodbcolumn can only be used for member variables of the annotation class.

@Retention:

 @Retention defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler, while others are compiled in the class file The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution because annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation.

  Function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the annotation being described is valid)

 The values (Retentionpoicy) are:

1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)

The Retention meta-annotation type has a unique value as a member, and its value is derived from the enumeration type value of Java.lang.annotation.RetentionPolicy. The concrete examples are as follows:

@Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @interface Column {public    String name () Default "FieldName";    Public String setfuncname () default "SetField";    Public String getfuncname () default "GetField";     public boolean defaultdbvalue () default false;}

The attribute value of the retentionpolicy of column annotations is rutime so that the annotation processor can get the property value of the annotation by reflection, thus doing some logic processing of the runtime

@Documented:

  @ Documented is used to describe other types of annotation that should be used as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members.

@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Column {public    String name () default "FieldName";    Public String setfuncname () default "SetField";    Public String getfuncname () default "GetField";     public boolean defaultdbvalue () default false;}

@Inherited:

  @Inherited meta-annotation is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. If a annotation type that uses the @inherited modifier is used for a class, the annotation will be used for subclasses of that 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 the 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.

Instance code:

/** *  * @author peida * */@Inheritedpublic @interface Greeting {public    enum fontcolor{Bule,red,green};    String name ();    FontColor fontcolor () default Fontcolor.green;}

Custom annotations:

When you use @interface to customize annotations, the Java.lang.annotation.Annotation interface is automatically inherited and other details are automatically completed by the compiler. When you define annotations, you cannot inherit other annotations or interfaces. @interface is used to declare an annotation, in which each method actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be base type, Class, String, enum). You can declare the default value of a parameter through default.

  To define the annotation format:
Public @interface annotation name {definition body}

  Supported data types for annotation parameters:

1. All basic data Types (Int,float,boolean,byte,double,char,long,short)
2.String type
3.Class type
4.enum type
5.Annotation type
6. Arrays of all types above

How to set the parameters of the annotation type:
First, it can only be decorated with public or default access rights. For example, String value (); Here the method is set to Defaul default type;
Second, parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and string,enum,class,annotations data types, As well as these types of arrays. For example, String value (), where the parameter member is string;
Thirdly, if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses. Example: The following example Fruitname annotation has only one parameter member.

Simple custom annotations and examples of using annotations:

Package Annotation;import Java.lang.annotation.documented;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target;/* * * Fruit Name NOTE * @author Peida * */@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @ Interface Fruitname {    String value () Default "";}
Package Annotation;import Java.lang.annotation.documented;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target;/* * * Fruit Color Annotations * @author Peida * */@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @ Interface Fruitcolor {    /**     * Color Enumeration     * @author Peida * */public    enum color{bule,red,green};        /**     * Color Properties     * @return     *    /color Fruitcolor () default Color.green;}
Package Annotation;import annotation. Fruitcolor.color;public class Apple {        @FruitName ("Apple")    private String applename;        @FruitColor (fruitcolor=color.red)    private String AppleColor;                    public void Setapplecolor (String applecolor) {        this.applecolor = AppleColor;    }    Public String Getapplecolor () {        return applecolor;    }            public void Setapplename (String applename) {        this.applename = applename;    }    Public String Getapplename () {        return applename;    }        public void DisplayName () {        System.out.println ("The name of the fruit is: Apple");}    }

Default values for annotation elements:

  The annotation element must have a definite value, either specified in the default value of the definition annotation, or specified when the annotation is used, and the value of a non-basic type of annotation element cannot be null. Therefore, using an empty string or 0 as the default value is a common practice. This constraint makes it difficult for the processor to represent the presence or absence of an element, because in each annotation declaration, all elements are present and have corresponding values, in order to circumvent this constraint, we can only define special values, such as an empty string or a negative number, once to indicate that an element does not exist, and when defining annotations, This has become a customary usage. For example:

1 package annotation; 2  3 import java.lang.annotation.Documented; 4 import java.lang.annotation.ElementType; 5 import Java.lang.annotation.Retention; 6 Import Java.lang.annotation.RetentionPolicy; 7 Import Java.lang.annotation.Target; 8  9/**10  * Fruit Provider Notes  * @author peida12  *13  */14 @Target (Elementtype.field) @Retention ( Retentionpolicy.runtime) @Documented17 public @interface fruitprovider {     /**19      * Supplier number *      @return21 C10/>*/22 public     int id () default-1;23     /**25      * Supplier name *      @return27      */28     public string name () default "";     /**31      * Supplier Address:      * @return33 */34 public     string Address () Default ""; 35}

Annotations are defined and, when needed, annotated information is given to related classes, class attributes, and annotations can be said to be of no practical value if there is no response to the annotated message processing flow. How to make annotations really play a role, mainly in the annotation processing method, next we will learn the annotation information acquisition and processing! V

In-depth understanding of Java: Annotations (Annotation) Getting Started with custom annotations

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.