Foreword # #

Now that we have a glimpse of the system’s built-in annotations, let’s look at how to customize annotations.

This article is reproduced from the authors of an article, because he is too good, very suitable for new to annotate the friend to see, the connection of the original address: http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html.

# # text

Yuan comments:

The meta-annotation is responsible for the annotation of other annotations. Java5.0 defines four standard meta-annotation types that are used to provide annotations for other annotation types. Meta annotations defined by Java5.0:

The types 1.@Target, 2.@Retention, 3.@Documented, 4.@Inherited and the classes they support are found in the java.lang.annotation package. Let’s take a look at what each meta-annotation does and how the corresponding sub-parameters are used.

@ Target:

@target specifies the range of objects that the Annotation decorates: Annotations can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, constructors, member variables, enumerated values), method parameters, and local variables (such as loop variables, catch parameters). Target is used in the Annotation type declaration to clarify the target it modifies.

Purpose: To describe the scope of use of the annotation (i.e. where the described annotation can be used)

The values (ElementType) are:

LOCAL_VARIABLE used to describe local variables 4.METHOD used to describe methods 5.PACKAGE Used to describe packages 6.PARAMETER Used to describe parameters 7.TYPE: Used to describe classes, interfaces (including annotation types), or enum declarations

Example:

@target (elementtype.type) public @interface Table {/** * data Table name annotation, default value is class name * @return
     */
    public String tableName() default "className";
}

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

}
Copy the code

The annotation Table can be used for annotation classes, interfaces (including annotation types), or enum declarations, while the annotation NoDBColumn can only be used for annotation class member variables.

@ Retention:

@Retention defines how long the Annotation is retained: some annotations only appear in source code and are discarded by the compiler; Others are compiled in class files; Annotations compiled in a class file may be ignored by the virtual machine, while others will be read when the class is loaded (note that class execution is not affected, since annotations and classes are used separately). Using this meta-annotation, you can limit the “life cycle” of an Annotation.

Purpose: Indicates the level at which the annotation information needs to be saved and is used to describe the lifecycle of the annotation (i.e., to what extent the described annotation is valid)

The values are as follows:

1.SOURCE: valid in the SOURCE file (i.e. reserved) 2.CLASS: valid in the CLASS file (i.e. reserved) 3.RUNTIME: valid at RUNTIME (i.e. reserved at RUNTIME)

Retention meta – the annotation type has a unique value as a member of its values from Java. Lang. The annotation. RetentionPolicy enumeration values. 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;
}
Copy the code

The value of the RetentionPolicy attribute for Column is RUTIME, which allows the annotation processor to reflect the value of the attribute for the Column to do some runtime logic

@Documented:

Documented indicates that other types of annotations should be considered a public API for the annotated program member and therefore Documented by a tool such as Javadoc. Documented is a marked annotation that has no member.

@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;
}
Copy the code

@ Inherited:

An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited. If an annotation type with the @Inherited annotation is applied to a class, the annotation will be applied to a subclass of that class.

Note: The @Inherited Annotation type is Inherited by a subclass of the annotated class. A class does not inherit annotations from the interface it implements, and a method does not inherit annotations from the method it overloads.

When annotation annotation annotated by @Inherited Annotation type is Retention retentionPolicy. RUNTIME, the reflection API enhances this inheritance. When we use java.lang.reflect to query an annotation of @Inherited Annotation type, reflection code inspection will work: Inspect the class and its parent until the specified annotation type is found or reaches the top of the class inheritance structure.

Example code:

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

Custom annotations:

When using the @ interface custom annotations, automatic inherited Java. Lang. The annotation. The annotation interface, the compiler automatically other details. When defining annotations, you cannot inherit from other annotations or interfaces. @interface is used to declare an annotation, and each of these methods is actually declaring 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 type, Class, String, or enum). You can declare default values for parameters with default.

Define 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. The type String (3) 4 Class type enum type 5. 6 the Annotation type. All of the above types of arrays

The Annotation type contains the following parameters:

First, you can only use the public or default access modifier. For example, a String value (); I’m going to set this method to the default defaul type;

Second, members can only use basic types of parameters byte, short, char, int, long, float, double, Boolean eight basic data types, and String, Enum, Class, annotations and other data types, and that some types of arrays. For example, a String value (); The parameter member here is String;

Third, if there is only one parameter member, it is best to set the parameter name to “value” followed by parentheses. Example: In the following example, the FruitName annotation has only one parameter member.

Simple examples of custom annotations and 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; /** * @author Peida ** / @Target(elementtype.field) @Retention(RetentionPolicy.runtime) @documented Public @interface FruitName { String value() default"";
}
Copy the code
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 @author peida ** / public enum Color{BULE,RED,GREEN}; /** * color attribute * @return
     */
    Color fruitColor() default Color.GREEN;

}
Copy the code
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"); }}Copy the code

Default values for annotation elements:

An annotation element must have a definite value, either specified in the default value used to define the annotation or when using the annotation. The value of an annotation element of a non-primitive type cannot be NULL. Therefore, using an empty string or 0 as the default is a common practice. This constraint may make it harder for the processor to show the existence of an element or the lack of status, because each statement annotations, all elements are present, and have the corresponding values, in order to circumvent this constraint, we can define some special values, such as an empty string or negative, said an element does not exist at a time, when the custom annotation, it has become a habit. Such as:

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 FruitProvider {/** * Vendor number * @return*/ public int id() default -1; /** * Supplier name * @return
     */
    public String name() default ""; /** * Supplier address * @return
     */
    public String address() default "";
}
Copy the code

Annotations are defined and annotated to relevant classes and class attributes as needed. Without a responsive annotation process, annotations are practically useless. How to make annotations play a role, mainly lies in the annotation processing method, next we will learn the annotation information acquisition and processing!

# # to summarize

Here’s my summary:

1. Don’t be fooled by @interface, because it looks a lot like interface and is really just a type.

2. @target indicates what the annotation I define will be used to modify a CLASS, a FIELD or a METHOD.

3, @Retention refers to annotation life cycle, SOURCE, CLASS because the life cycle is short, we can’t get, so we use RUNTIME.

Now that we know how to customize annotations, how do we use them? In this case, the reflection mechanism introduced in the first article is used. In the next article, we will look at the use of reflection and annotations together.