Note Two Java custom annotation __java annotation

Source: Internet
Author: User
Tags reflection
To drill down into annotations, we have to be able to define our own annotations and use annotations, before we define our own annotations, we have to understand the syntax of the meta annotations and the related definition annotations that Java provides for us.

Meta Note:

The function of the meta annotation is to annotate other annotations. Java5.0 defines 4 standard meta-annotation types that are used to provide descriptions of other annotation types. Java5.0 defined meta Annotations:
1. @Target,
2. @Retention,
3. @Documented,
4. @Inherited
These types and the classes they support can be found in the Java.lang.annotation package. Let's take a look at the role of each meta annotation and the instructions for using the corresponding argument.

  @Target:

@Target describes the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, construction methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Using target in a annotation type of declaration can make it more explicit about the target that it modifies.

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

 values (ElementType) are:

1.CONSTRUCTOR: Used to describe the builder
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

Use instance:

@Target (elementtype.type) public
@interface Table {
    /**
     * Datasheet name annotation, 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, whereas note Nodbcolumn can be used only for member variables of the annotation class.

@Retention:

 @Retention defines how long the annotation is retained: Some annotation only appear in the source code and are discarded by the compiler, while others are compiled into 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 the class is not enforced because annotation is separated from the class in use). Use this meta-annotation to limit the lifecycle of annotation.

  role: 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 described annotation is valid)

 values (retentionpoicy) are:

1.SOURCE: Valid in the source file (that is, source file retention)
2.CLASS: Valid in class file (that is, class reservation)
3.RUNTIME: Valid at run time (that is, run-time reservation)

The Retention meta-annotation type has a unique value as a member whose value comes from the Java.lang.annotation.RetentionPolicy enumeration type value. Specific 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 Retentionpolicy property value of the column annotation is rutime so that the annotation processor can get the attribute value of the annotation through reflection, thus doing some run-time logical processing

@Documented:

  @ Documented is used to describe other types of annotation as public APIs that should be labeled as program members, so it can be documented as a tool such as Javadoc. Documented is a tagged annotation with no members.

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

@Inherited:

  A @Inherited meta annotation is a markup annotation @Inherited illustrates that a labeled type is inherited. If a annotation type using the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

Note: The @Inherited annotation type is inherited by subclasses of the annotated class. The class does not inherit annotation 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 annotation @inherited annotation type callout is retentionpolicy.runtime. If we use Java.lang.reflect to query a @inherited annotation type of annotation, the reflection code check expands to work: Check class and its parent class until the specified annotation type is found. Or to the top level of the class inheritance structure.

Instance code:

/**
 * * * 
 @author Peida * */
 @Inherited public
@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 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 the base type, Class, String, enum). You can declare the default value of a parameter via default.

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

  the supported data types for the 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. All of the above types of arrays

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

Simple custom annotations and use annotation instances:

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;

/**
 *
 @author peida * *
/@Target (Elementtype.field)
@Retention ( Retentionpolicy.runtime)
@Documented public
@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 Annotation * @author Peida */@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documented public @i
    
    Nterface Fruitcolor {/** * Color enumeration * @author Peida * */public enum color{Bule,red,green};

/** * Color Property * @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 ("Fruit name is: Apple");
    }

default value for callout element:

The annotation element must have a definite value, either specified in the default value of the definition annotation, or specified when using the annotation, the value of the callout element of the non base type is not nullable. Therefore, it is a common practice to use an empty string or 0 as the default value. This constraint makes it difficult for the processor to represent the presence or absence of an element, because all the elements exist in the declaration of each annotation, and all have corresponding values, in order to circumvent this constraint, we can only define special values, such as an empty string or a negative number, indicating that an element does not exist at one time, when defining annotations, This has become a habitual 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/**  Fruit Supplier Note *  @author peida
/@Target ( Elementtype.field
@Retention (retentionpolicy.runtime) @Documented public
@interface Fruitprovider {     /**      * supplier number      @return     /Public int id () default-1;     
/** *     name
of      supplier      * @return
/public     String name () Default "";     
/** to      suppliers address      @return     /Public String () Default "";
35}

The annotation is defined and the annotation information is added to the relevant class, class attribute when needed, and the annotation can be said to have no practical value if there is no response to the annotation processing process. How to make annotations really play a role, mainly in the annotation processing method, next we will learn the annotation information acquisition and processing.

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.