Getting Started with JAVA Annotation Annotation Custom Annotation

To learn about annotations in depth, we must be able to define our own annotations and use annotations. Before defining our own annotations, we must understand the meta-annotations provided by Java and the syntax of related definition annotations.

 

Article from: http://www.pm-road.com/index.php/2015/12/04/587/

Meta annotations:

The role of meta-annotations is to annotate other annotations. Java 5.0 defines four standard meta-annotation types, which are used to provide descriptions for other annotation types. Meta annotations defined by Java5.0:
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 sub-parameters.

@Target:

@Target specifies the scope of objects modified by Annotation: Annotation can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, constructors, member variables, enumeration values), method parameters and Local variables (such as loop variables, catch parameters). The use of target in the declaration of the Annotation type can be more explicit about the target of its modification.

  Role: used to describe the scope of use of the annotation (ie: where the described annotation 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 the local variables
4.METHOD: used to describe the method
5.PACKAGE: used to describe the package
6.PARAMETER: used to describe the parameters
7.TYPE: used to describe classes, interfaces (including annotation types) or enum declarations

Example of use:

@Target(ElementType.TYPE)
public @interface Table {
    /**
     * Data table name annotation, the default value is the class name
     * @return
     */
    public String tableName() default "className";
}

@Target(ElementType.FIELD)
public @interface NoDBColumn {

}

Annotation Table can be used to annotate classes, interfaces (including annotation types) or enum declarations, while annotation NoDBColumn can only be used to annotate member variables of classes.

  @Retention:

 @Retention defines how long the Annotation is retained: some Annotations only appear in the source code and are discarded by the compiler; others are compiled in the class file; Annotation compiled in the class file may be virtualized The machine ignores, and others will be read when the class is loaded (please note that it does not affect the execution of the class, because Annotation and class are used separately). Use this meta-Annotation to limit the "lifetime" of Annotation.

Function: Indicates at what level the annotation information needs to be saved to describe the life cycle of the annotation (ie: in what scope is the described annotation valid)

 The values ​​(RetentionPoicy) are:

1.SOURCE: valid in the source file (that is, the source file is retained)
2.CLASS: valid in the class file (that is, the class is retained)
3.RUNTIME: valid at runtime (that is, the runtime is retained)

The Retention meta-annotation type has a unique value as a member, and its value comes from the enumeration type value of java.lang.annotation.RetentionPolicy. 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 attribute value of the RetentionPolicy of the Column annotation is RUTIME, so that the annotation processor can obtain the attribute value of the annotation through reflection, so as to do some runtime logic processing

  @Documented:

  @Documented is used to describe the public API that other types of annotations should be used as annotated program members, and thus can be documented by tools such as javadoc. Documented is a markup 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:

  The @Inherited meta-annotation is a marker annotation, @Inherited states that an annotated type is inherited. If a @Inherited annotation type is used in a class, the annotation will be used in subclasses of that class.

Note: The @Inherited annotation type is inherited by subclasses of the marked class. A class does not inherit annotations from interfaces it implements, and methods do not inherit annotations from methods it overrides.

When the Retention of the annotation marked by the @Inherited annotation type is RetentionPolicy.RUNTIME, the reflection API enhances this inheritance. If we use java.lang.reflect to query an annotation of type @Inherited annotation, the reflection code inspection will work: checking the class and its superclass until the specified annotation type is found, or it reaches the top level of the class inheritance structure.

Example code:

/**
 *
 * @author farts
 *
 */
@Inherited
public @interface Greeting {
    public enum FontColor{ BULE,RED,GREEN};
    String name();
    FontColor fontColor() default FontColor.GREEN;
}

Custom annotations:

When using @interface to customize the annotation, the java.lang.annotation.Annotation interface is automatically inherited, and other details are automatically completed by the compiler. When defining an annotation, other annotations or interfaces cannot be inherited. @interface is used to declare an annotation where 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 basic types, Class, String, enum). The default value of a parameter can be declared by default.

Definition 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. Array of all the above types

How should the parameters in the Annotation type be set:
first, they can only be modified with public or default access rights. For example, String value(); here, the method is set to the default type of defaul;
second, the parameter member Only eight basic data types of basic types byte, short, char, int, long, float, double, boolean and data types such as String, Enum, Class, annotations, and arrays of these types can be used. For example, String value() ; The parameter member here is String;
Third, if there is only one parameter member, it is best to set the parameter name as "value", followed by parentheses. Example: The FruitName annotation in the following example 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 annotation
 * @author farts
 *
 */
@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 farts
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    /**
     * Color enumeration
     * @author farts
     *
     */
    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 using the annotation. The value of the annotation element of a non-primitive type cannot be null. 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 express the presence or absence of an element, because in the declaration of each annotation, all elements are present and have corresponding values. In order to circumvent this constraint, we can only define some special Values, such as the empty string or a negative number, indicate that an element does not exist at a time, which has become an idiom when defining annotations. E.g:

 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  * 水果供应者注解
11  * @author peida
12  *
13  */
14 @Target(ElementType.FIELD)
15 @Retention(RetentionPolicy.RUNTIME)
16 @Documented
17  public @interface FruitProvider {
 18      /** 
19       * provider number
 20       * @return 
21       */ 
22      public  int id() default -1 ;
 23      
24      /** 
25       * provider name
 26       * @return 
27       */ 
28      public String name() default "" ;
 29      
30      /** 
31       * Supplier address
 32       * @return 
33       */ 
34     public String address() default "";
35 }

 

Define annotations, and add annotation information to related classes and class attributes when needed. If there is no corresponding annotation information processing process, annotations can be said to have no practical value. How to make annotations work really depends on the annotation processing method. Next, we will learn the acquisition and processing of annotation information!

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327040313&siteId=291194637