Explanation of enumeration class and annotation

Notes:

In the actual development process, we often use annotations. If you don't understand annotations in the development process, it means that you are not a qualified programmer. Therefore, it is necessary for us to have an in-depth understanding of annotations.

Annotation can be used like modifiers to modify the declarations of packages, classes, constructors, methods, member variables, parameters and local variables. This information is stored in the "name=value" pair of annotation.

There are three basic annotations built into the jdk: @ Override @Deprecated @SuppressWarnings

When we learn the basics of JAVA, we often use the following annotations:

@Override tells the compiler that this method is a method that overrides the parent class

@WebServlet("/test") indicates that a class is a servlet. The web container will recognize this annotation and call it at run time.

@Controller("/test") indicates that a class is a controller and tells the spring framework that this class is a controller.

Annotation and annotation are two completely different things. They look a little similar. In fact, they are completely different. Annotation will affect the operation of the program. Comments are for developers and will not affect the compilation and operation of the program. Annotations are not for developers, but for programs, which will affect the compilation and operation of programs, such as compilers, tomcat and frameworks.

1.1 scope of notes

To customize and develop a web container, the basic function is to load servlets, and its life cycle needs to be managed. Therefore, we must first identify which classes in the program are servlets. When the program starts, scan all classes, find the classes with @ WebServlet annotation, and load them (similar to the startup process of spring IOC container).

@WebServlet works when the program is running, so JAVA defines its scope as RUNTIME

@Override is to show the compiler that it is hungry. When the compiler recognizes the method containing the @ override annotation, it checks the corresponding method of its upper parent class. If it exists, it passes. Otherwise, an error is reported.

@Override works when compiling, and JAVA specifies its scope as SOURCE

@Test is used to generate test code. It is generally used in the framework. The scope of action is SOURCE

JDK5.0 provides four standard meta annotation types: target retention documented inherited

one 2@Target Specify where the annotation is directed

ElementType:

ElementType.TYPE: for classes and interfaces

ElementType.FIELD: for member variables

ElementType.METHOD: method for members

ElementType.PARAMETER: for method parameters

ElementType.CONSTRUCTOR: for constructor

ElementType.PACKAGE: for packages

ElementType.ANNOTATION: for annotation

1.3 @Retention specifies the reserved field of the annotation

It can also be understood as the lifetime of the annotation

RetentionPolicy:

RetentionPolicy.SOURCE source code level, which is processed by the compiler and will not be retained after processing

RetentionPolicy.CLASS annotation information is retained in the class file corresponding to the class. This is a default behavior, that is, if it is not specified, it is him by default.

RetentionPolicy.RUNTIME is read by the JVM and used at runtime, that is, only annotations declared as runtime declaration cycles can be obtained through reflection.

one 4@Documented : (less in actual use)

It is used to specify that the Annotation class modified by this meta Annotation will be extracted into a document by the javadoc tool. By default, javadoc does not include annotations.

Annotations defined as Documented must have the Retention value set to RUNTIME

one 5@Inherited : (less in actual use)

The Annotation modified by him will be Inherited. If a class uses an Annotation modified by this @ Inherited, its subclass will automatically have the Annotation.

For example, if the custom annotation marked with @ Inherited annotation is marked at the class level, the subclass can inherit the annotation at the parent level.

In practical application, it is less used

1.6 custom annotation

package com.annotationpractice;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//Add a source annotation to indicate what the current annotation is for
@Target(ElementType.METHOD)//Indicates that this annotation can only be added to the method
@Retention(RetentionPolicy.RUNTIME)//Indicates that the annotation can only be called at run time
public @interface InitMethod {
}

package com.annotationpractice;

public class InitDemo {
    @InitMethod
    public void init(){
        System.out.println("init......");
    }

    public void test(){

    }
}
package com.annotationpractice;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Use of test annotations
 */
public class Test {
    public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> clazz = Class.forName("com.annotationpractice.InitDemo");
        Method[] methods = clazz.getMethods();
        if(null != methods){
            for (Method method : methods) {
                boolean flagInitMethod = method.isAnnotationPresent(InitMethod.class);//See if there is this annotation in the method
                if(flagInitMethod){
                    method.invoke(clazz.getConstructor(null).newInstance(null),null);
                }
            }
        }
    }
}
Operation results: init......

Note: Custom annotations must be accompanied by information processing flow to be meaningful. In other words, reflection must be used.

New feature of annotation in jdk8 1.7 repeatable annotation type annotation

Repeatable annotation

① Declare @ repeatable on MyAnnotation, and the member value is myannotations class

② Meta annotations such as Target and Retention of MyAnnotation are the same as MyAnnotations

Write this note before jdk8:

////This was written before jdk8
//@MyAnnotations({@MyAnnotation(value = "hi"),@MyAnnotation(value = "abc")})

jdk8 write this note:

@MyAnnotation(value = "abc")
@MyAnnotation(value = "hi")
package com.annotationpractice;

import com.sun.deploy.security.ValidationState;

import java.lang.annotation.*;
import java.lang.reflect.Type;

import static java.lang.annotation.ElementType.*;

/**
 * Custom annotation
 */
@Repeatable(MyAnnotations.class)
@Target({TYPE,FIELD,METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String[] value() default "hello";
}

package com.annotationpractice;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;

/**
 * Custom annotation
 */
@Target({TYPE,FIELD,METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotations {
    MyAnnotation[] value();
}

package com.annotationpractice;

/**
 * How to customize annotation reference @ suppressdrawing definitions
 * 1.Annotation declared as @ interface
 * 2.Internally defined members, usually represented by value
 * 3.You can specify the default value of the member, which is defined by default
 * 4.If the user-defined annotation has no members, it indicates that it is an identification function
 *
 */
//@MyAnnotation(value = "hi") / / of course, it can be unspecified here
////This was written before jdk8
//@MyAnnotations({@MyAnnotation(value = "hi"),@MyAnnotation(value = "abc")})
@MyAnnotation(value = "abc")
@MyAnnotation(value = "hi")
public class Person {
    private String name;
    private int age;

//    @MyAnnotation / / because the value has been specified inside the annotation, you can not write the value here if there is no special need.
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

type annotation

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

ElementType.TYPE_USE: indicates that the annotation can be written in any statement using type

package com.annotationpractice;

import com.sun.deploy.security.ValidationState;

import java.lang.annotation.*;
import java.lang.reflect.Type;

import static java.lang.annotation.ElementType.*;

/**
 * Custom annotation
 */
@Repeatable(MyAnnotations.class)
@Target({TYPE,FIELD,METHOD,TYPE_PARAMETER,TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String[] value() default "hello";
}

package com.annotationpractice;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * type annotation 
 */
public class Generic<@MyAnnotation T> {
    public void show() throws @MyAnnotation RuntimeException{
        ArrayList<@MyAnnotation String> list = new ArrayList<>();
        int num=(@MyAnnotation int) 10L;
    }
}

Case: simple test framework

Reference website: https://blog.csdn.net/zzu_seu/article/details/104673681

Keywords: Java

Added by Mhz2020 on Mon, 27 Dec 2021 09:23:56 +0200