The introduction and use of Java annotations in detail

annotation

Annotation Basic Introduction

Annotation overview :

Java annotation (Annotation), also known as Java annotation, is an annotation mechanism introduced by JDK5.0.

Classes, constructors, methods, member variables, parameters, etc. in the Java language can be annotated with annotations.

The role of annotations :

Mark the classes, methods, and member variables in Java, and then perform special processing. As for the processing, it is determined by the business requirements.

For example: In the JUnit framework, a method marked with @Test can be executed as a test method, while an unmarked method cannot be executed as a test method.

insert image description here

custom annotation

Custom annotations :

Custom annotation is to make an annotation by yourself to use

The format of a custom annotation is as follows :

public @interface 注解名称 {
    
    
  	public 属性类型 属性名() default 默认值 ;
}

Note :

The default value of custom annotation can be omitted;

Customization is public by default, and the public modifier can be omitted

Demo code :

Custom Annotation MyBook

public @interface MyBook {
    
    
    String name();
    String[] authors();
    // 给默认值
    double price() default 88.8;
}

Use custom annotations to annotate classes, variables, methods, etc.

@MyBook(name = "Java数据结构", authors = {
    
    "作者1", "作者2"})
public class AnnotationDemo {
    
    
    @MyBook(name = "Java数据结构1", authors = {
    
    "作者1", "作者2"})
    public static void main(String[] args) {
    
    
        @MyBook(name = "Java数据结构2", authors = {
    
    "作者1", "作者2"})
        int num = 0;
    }
}

special type :

value attribute, if there is only one value attribute, the value name can be omitted when using the value attribute!!

public @interface Book {
    
    
    // 只有一个value属性
    String value(); // 特殊属性
}
//@Book(value = "/delete")

@Book("cba") // 可以省略不写
public class AnnotationDemo {
    
    
}

But if there are multiple attributes, and multiple attributes have no default value, then the value name cannot be omitted;

If multiple attributes have default values, then the value name can be omitted.

// 多个值,	且其他值都有默认值
public @interface Book {
    
    
    String value(); // 特殊属性
    String name() default "一本书";
    double price() default 99.9;
}
//@Book(value = "/delete")

@Book("cba") // 可以省略不写
public class AnnotationDemo {
    
    
}

meta annotation

Meta annotation definition :

Meta annotations are annotations of annotations

There are two meta-annotations :

@Target: constrains where custom annotations can only be used,

@Retention: declare the life cycle of annotations

The values ​​that can be used in Target are defined in the ElementType enumeration class, and the common values ​​are as follows :

TYPE, indicating that the annotation can only annotate classes and interfaces

FIELD, indicating that the annotation can only annotate member variables

METHOD, indicating that the annotation can only annotate member methods

PARAMETER, indicating that the annotation can only annotate method parameters

CONSTRUCTOR, indicating that the annotation can only annotate the constructor

LOCAL_VARIABLE, indicating that the annotation can only annotate local variables

@Target({
    
    ElementType.FIELD, ElementType.METHOD}) // 表示自定义注解只能对成员变量和方法进行注解
public @interface MyTest {
    
    
}

The values ​​that can be used in Retention are defined in the RetentionPolicy enumeration class. Common values ​​are as follows ( generally not used, hope that the annotation will always exist ) :

SOURCE: Annotations only apply to the source code stage, and do not exist in the generated bytecode file

CLASS: The annotation works in the source code stage, the bytecode file stage, does not exist in the runtime stage, and the default value.

RUNTIME: annotations are used in the source code phase, bytecode file phase, and runtime phase (commonly used in development)

@Retention(RetentionPolicy.RUNTIME) // 表示注解一直存在
public @interface MyTest {
    
    
} 

Annotation analysis

Annotation analysis :

The operation of annotations often needs to be parsed. The parsing of annotations is to judge whether there are annotations, and if there are annotations, the content is parsed out.

Interfaces related to annotation parsing :

Annotation: the top-level interface of annotations, all annotations are objects of type Annotation

AnnotatedElement: Annotated element interface, which defines the parsing methods related to annotation parsing

The annotation method is as follows :

All reflected class components Class, Method, Field, and Constructor implement the AnnotatedElement interface and they all have the ability to parse annotations

method illustrate
Annotation[] getDeclaredAnnotations() Get all annotations used on the current object, returning an array of annotations.
getDeclaredAnnotation(Class<T> annotationClass) Obtain the corresponding annotation object according to the annotation type
isAnnotationPresent(Class<Annotation> annotationClass) Determine whether the current object uses the specified annotation, if used, return true, otherwise false

Tips for parsing annotations :

On which component the annotation is on, we will take which component object first.

For example, if an annotation acts on a member method, it is necessary to obtain the Method object corresponding to the member method, and then take the above annotation

For example, if the annotation acts on the class, the Class object of the class is required, and then the above annotation is required

For example, if the annotation acts on a member variable, it is necessary to obtain the Field object corresponding to the member variable, and then take the above annotation

Annotation analysis case practice :

The steps are as follows :

To define the annotation Book, the requirements are as follows:

  • Contains attributes: String value() book title
  • Include attribute: double price() price, the default value is 100
  • Contains attributes: String[] authors() multiple authors
  • Limit where annotations can be used: on classes and member methods
  • Specify the effective range of annotations: RUNTIME

Define the BookStore class and use Book annotations on the class and member methods

Define the AnnotationDemo test class to obtain the data on the Book annotation

Demo code :

Implement custom annotation Book

@Target({
    
    ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Book {
    
    
    String value();
    double price() default 100;
    String[] authors();
}

Define the BookStore class, and use Book annotations on the class and member methods

@Book(value = "大话西游", authors = {
    
    "作者a", "作者b"})
public class BookStore {
    
    
    @Book(value = "盗梦空间", price = 10.99,authors = {
    
    "作者1", "作者2"})
    public void bubBook() {
    
    
        System.out.println("买书成功");
    }
}

Define the AnnotationDemo test class to obtain the data on the Book annotation

public class AnnotationDemo {
    
    
    public static void main(String[] args) {
    
    
        // 获取Class类对象
        Class c = BookStore.class;

        // 判断该类上是否存在Book.class这个注解对象
        if (c.isAnnotationPresent(Book.class)) {
    
    
            // 存在获取BookStore类的Book.class这个注解对象
            Book book = (Book) c.getAnnotation(Book.class);

            // 查看注解内容
            System.out.println(book.value()); // 大话西游
            System.out.println(book.price()); // 100.0
            System.out.println(Arrays.toString(book.authors())); // [作者a, 作者b]
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_71485750/article/details/127748829