Custom comment [fine]

Custom annotation

I. Preface

In the development process, various xml configuration files cause tedious configuration steps, and the code logic is not intuitive and other problems have been gradually replaced by annotations. Now, there are various annotations everywhere in the coding, so how to customize an annotation to use in the project?

2, What you need to know about custom annotations

&Define annotation type: define a new annotation class using @ interface keyword, the same as defining a class.

&Custom annotation class inheritance relationship: the custom annotation class automatically inherits the java.lang.annotation.Annotation interface

&Custom annotation class member variable: the member variable defined in the custom annotation class is declared in the form of parameterless method. The name of the method is the variable name, and the return value type of the method is the variable type. (member variables are also called configuration parameters)

* for example: String name() {} - > name is the variable name and String is the variable type.

&Types of member variables: eight basic data types, String type, Class type, enum type, Annotation type, arrays of all the above types

&Custom annotation default value: when creating annotation class, if you need to create initial value. You can use default to create an initial value for a variable. The variable name usually uses value

* for example: boolean value() default true

&If a defined annotation contains configuration parameters, the parameter value must be specified when it is used, unless it has a default value. The format is "parameter name = parameter value". If there is only one parameter member and the name is value, "value =" can be omitted

3, Custom annotation

Using the content of the custom annotation described above, create an annotation to deepen the understanding of the above content.

  • Create Note
/**
 * Use @ interface keyword to define an annotation
 * The custom annotation automatically inherits the java.lang.annotation.Annotation interface by default
 */

public @interface MyAnnotation {

}
  • Create annotation without initial value parameter configuration
public @interface MyAnnotation {
    // Define annotation member variable, value is variable name, String is variable type. Member variable is also called parameter configuration
    // No parameter configuration specified for initial value 
    String value();
}

Using an annotation without an initial value, you need to assign a value to the parameter.

// Use annotations to assign values to parameters
@MyAnnotation(value = "Wang Gang")
public class AnnotationTest {
    private static String name="Zhang Wei";

    public static void main(String[] args) {
        System.out.println(name);
    }

}
  • Create annotation for parameter configuration initialized value
public @interface MyAnnotation {
    /**
     * 1.Initializing parameter configuration values using the default keyword
     * 2.If there is only one parameter configuration, it is recommended to use value as the parameter configuration name
     * @return
     */
    String value()  default "Cheung Kwok Keung";
}

The annotation of initialization configuration parameter can be used without assignment

// Initializes parameter configuration. No assignment is required when using annotation
@MyAnnotation
public class AnnotationTest {
    private static String name="Zhang Wei";

    public static void main(String[] args) {
        System.out.println(name);
    }

}

4, Meta annotation

Meta annotation: annotation used to decorate other annotations is meta annotation

Four types of meta annotation: Retention, Target, Documented, Inherited

@ Retention: Specifies the Annotation lifecycle. @Rentention contains a member variable of type RetentionPolicy. When using @ rentention, you must specify a value for the value member variable

* RetentionPolicy.SOURCE: valid in the source file (i.e. source file retention), the compiler directly discards the comments of this policy.

* RetentionPolicy.CLASS: valid in the class file (i.e. class reservation). When running a Java program, the JVM will not retain the annotations. This is the default

* RetentionPolicy.RUNTIME: valid at run time (i.e. reserved at run time), the JVM will keep comments when the Java program is run on the line. The program can get the comment through reflection.

Target: defines which program elements in the code the custom annotation can be used for. @Target also contains a member variable named value.

* TYPE: restrict the application of custom annotation to the class

* CONSTRUCTOR: restrict custom annotations to constructors

* FIELD: restrict custom comments to property fields

* METHOD: limit the application of custom annotation to METHOD

* PARAMETER: restrict the application of custom annotation to method formal parameters

* local "variable: restrict the application of custom annotation to local variables

* annotation? Type: restrict custom annotation to annotation type

* PACKAGE: restrict the application of custom annotation to PACKAGE

@Documented: define whether Javadoc documents are generated on the classes of annotation application. By default, Javadoc does not include annotations. Annotations defined as documented must have Retention set to RUNTIME.

@Inherited: the Annotation decorated by it will be inherited. If a class uses Annotation decorated by @ inherited, its subclass will automatically have the Annotation.

5, Meta annotation usage

  • Retention meta Annotation: Specifies the lifecycle of Annotation. The lifecycle range value is described in the meta Annotation above.
//Define the lifecycle of a custom annotation
@Retention(RetentionPolicy.SOURCE)

public @interface MyAnnotation {
    /**
     * 1.Initializing parameter configuration values using the default keyword
     * 2.If there is only one parameter configuration, it is recommended to use value as the parameter configuration name
     * @return
     */
    String value()  default "Cheung Kwok Keung";
}
  • @Target: defines which program elements in the code the custom annotation can be used for. @Target also contains a member variable named value.
/**
 * Used to specify which program elements can be decorated by the decorated Annotation
 */
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
    /**
     * 1.Initializing parameter configuration values using the default keyword
     * 2.If there is only one parameter configuration, it is recommended to use value as the parameter configuration name
     * @return
     */
    String value()  default "Cheung Kwok Keung";
}

Target only defines METHOD, so this annotation can only be used on METHOD.

//Defining annotations can only be used on Methods
@Target({METHOD})

@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
    /**
     * 1.Initializing parameter configuration values using the default keyword
     * 2.If there is only one parameter configuration, it is recommended to use value as the parameter configuration name
     * @return
     */
    String value()  default "Cheung Kwok Keung";
}

Test Target usage

  • @ Documented: define whether Javadoc documents are generated on the classes of annotation application. By default, Javadoc does not include annotations. Annotations defined as Documented must have Retention set to RUNTIME.
@Documented
public @interface MyAnnotation {
    /**
     * 1.Initializing parameter configuration values using the default keyword
     * 2.If there is only one parameter configuration, it is recommended to use value as the parameter configuration name
     * @return
     */
    String value()  default "Cheung Kwok Keung";
}

The TestApp class uses the @ Documented annotation. After generating JavaDoc documents, the annotation name used by this class will appear in the documents.

class TestApp{
    /**
     * This method is a test method
     */
    @MyAnnotation
    public static void test() {
        System.out.println("test method");
    }
}
  • @Inherited: the Annotation decorated by it will be inherited. If a class uses Annotation decorated by @ inherited, its subclass will automatically have the Annotation.
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {
    /**
     * 1.Initializing parameter configuration values using the default keyword
     * 2.If there is only one parameter configuration, it is recommended to use value as the parameter configuration name
     * @return
     */
    String value()  default "Cheung Kwok Keung";
}

Define a subclass to inherit the parent class. Only add an annotation modified by @ Inherited on the parent class. The subclass does not add an annotation.

/**
 * Define Tests as the parent class, and TestApp inherits the parent class. Add an annotation @ MyAnnotation modified by @ Inherited to the parent class
 */
@MyAnnotation
class Tests{
    public static void test() {
        System.out.println("Parent class");
    }
}

class TestApp extends Tests{
    /**
     * This method is a test method
     */
    public static void test() {
        System.out.println("Subclass");
    }
}

Test class: obtain the annotation information of the subclass through reflection, indicating that the subclass inherits the annotation of the parent class.

public class AnnotationTest {
    
    public static void main(String[] args) {
        
        //Reflection gets the bytecode file of the subclass.
        Class clazz = TestApp.class;
        //Get annotation information of subclass
        Annotation[] annotations = clazz.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println(annotations[i]);
        }

    }

}

Test results

@day.annotation.MyAnnotation(value = Zhang Guoqiang)

6, Java 8 annotation new features

  • @Repeatable: repeatable annotation. The same annotation is used repeatedly on a class.

How to use repeated annotation:

Two annotations need to be defined, assuming the annotation names are A and B

①. Declare @ Repeatable on the A annotation. The member value is B annotation Name: B.class

②. The configuration type of B annotation parameter must be an array of type A: A[] value();

②. The Target and Retention meta annotations of annotation A are the same as those of annotation B.

  • Duplicate annotation instance

A note

//Repeated annotations
@Repeatable(B.class)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})

public @interface A {
    String value() default "Hello My is A";
}

B note

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface B {
    A[] value();
}

Test class

public class App {
    //Reuse annotations
    @A("My is name A")
    @A("My is name B")

    public void test() {
        System.out.println("Test class");
    }
}
  • @ Target annotation extension parameter

java8 adds two parameters to the parameter type of @ Target so that annotations can be applied anywhere.

TYPE_PARAMETER: indicates that the annotation can be written in the declaration statement of type variable (such as generic declaration)

Type Ou use: indicates that the annotation can be written in any statement using the type

Annotation @ Target annotation instance

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR,LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})

public @interface A {
    String value() default "Hello My is A";
}

Test class

// Type > parameter type uses annotations on generics
public class App<@A T> {
    /**
     * TYPE_USE Use annotations for exceptions, collections, and type conversions
     */
    public void test(T t) throws @A RuntimeException{
        List<@A String> list = new ArrayList<>();

        int num = (@A int) 10L;
        System.out.println("Test class");
    }
}

 

315 original articles published, 117 praised, 420000 visitors+
His message board follow

Tags: Java jvm xml

Posted on Mon, 16 Mar 2020 10:00:30 -0400 by grabber_grabbs