The use of annotation Annotation in-depth understanding of annotations in Java Custom annotation meta annotations

annotation

1. Concept

(1) Annotation: used to explain the program, for the computer to see, new features after JDK1.5
Usage:@注解名称

(2) Annotation: Describe the program in text for the coders

2. Function

(1) Write a document
Generate a doc document from the annotations identified in the code:

① Create a class

/**
 * 注解javadoc演示
 * @author 周杰伦  表示此类(文档)作者
 * @version 1.0  表示此类(文档)的版本
 * @since 1.8  表示从JDK1.8之后可以使用此类
 */
public class AnnoDemo1 {
    
    
    /**
     * 计算两数的和
     * @param a 整数
     * @param b 整数
     * @return 两数的和
     */
    public int add(int a, int b ){
    
    
        return a + b;
    }
}

② Use javadoc instructions for this java file

Insert picture description here
③ Open the doc file

Insert picture description here

(2) Code analysis: use reflection to analyze the code through the annotations in the code

(3) Compilation check: realize compile check through annotation, such as@Override

3. Custom annotations

(1) Format

public @interface 注解名称 {
    
    
// 属性列表;
}

(2) Essence

Annotation is essentially an interface that inherits the Annotation interface by default, as follows:

public interface 自定义注解 extends java.lang.annotation.Annotation {
    
    }

(3) Attributes in annotations

Annotated attributes are abstract methods in the interface

Claim:

① The return value type of the property:
i. Basic data type
ii. String type String
iii. Enumeration
iiii. Note
iiiii. Array of the above types
Note: other types such as class type and void are not allowed

② After defining the attribute, you need to assign a value to the attribute when using it

// 自定义注解
public @interface MyAnno {
    
    
    //以下均为省略了abstract关键字的抽象方法

    Person per(); //枚举类型,其中有P1,P2

    MyAnno2 anno2(); // 注解类型,定义另一个注解MyAnno2

    String[] strs(); // 数组类型

    //使用default关键字给属性赋值,表示默认初始值,
    //则使用注解时,可以不给此属性赋值,而使用默认值
    int value() default 15; //基本数据类型
}
// 使用注解
// 数组赋值时,值使用{}包裹,如果数组中只有一个值,可以省略{}
@MyAnno(per = Person.P1, anno2 = @MyAnno2, strs={
    
    "bbb", "ccc"})
public class Worker {
    
     // 自定义类
    //成员变量、属性
}

note:

  1. If there is only one attribute in the annotation and the name is value, no matter what the type of value is, the value can be omitted when assigning to it, and the value can be directly defined, such as@SuppressWarnings(“all”)

  2. Multiple different annotations can be used at the same time for the same class or method

4. Meta annotations

The annotations used to describe the annotations. Write meta annotations in the upper line of the custom annotations. There are four types:

(1) @Target:Describe the position where the annotation can function.
Attribute: ElementType[] value(); Among them, ElementType is an enumerated type, commonly used value:

  • TYPE means it can act on the class
  • METHOD means that it can act on methods
  • FIELD means it can act on variables

(2) @Retention: Describe the stage at which the annotation is retained.
Attribute: RetentionPolicy value(); where RetentionPolicy is an enumerated type, and its value is:

  • RUNTIME means that the current annotation will be kept in the class file and read by the JVM. This value is the most commonly used, and can also take the value SOURCE, CLASS

(3) @Documented: Descriptive comments can be extracted into API documents

(4) @Inherited: Descriptive annotations can be inherited: if the parent class uses the annotation described by this meta-annotation, the subclass that inherits this class will automatically be described by this annotation even if it does not write any annotations

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//自定义注解Pro
public @interface Pro {
    
    
    String className();
    String methodName();
}

5. Get the attribute value of the annotation

// 使用上述自定义注解Pro
@Pro(className = "cn.itcast.annotation.Demo1", methodName = "show")
public class ReflectTest {
    
    
    public static void main(String[] args) throws Exception {
    
    
        // 1. 使用该类的字节码文件对象解析注解
        Class<ReflectTest> reflectTestClass = ReflectTest.class;
        // 2. 获取指定的注解对象
        Pro an = reflectTestClass.getAnnotation(Pro.class);
        // 第二步其实就是在内存中生成了一个该注解接口的子类实现对象
        
        /*
            public class ProImpl implements Pro{
                public String className(){
                    return "cn.itcast.annotation.Demo1";
                }
                public String methodName(){
                    return "show";
                }
            }
        */
        
        // 3. 调用注解对象中定义的抽象方法,获取返回值
        String className = an.className();
        String methodName = an.methodName();
        System.out.println(className); //cn.itcast.annotation.Demo1
        System.out.println(methodName); //show
    }
}

Note: When using multiple annotations, call the null parameter getAnnotation() method of the Class object to get all annotation objects and return Annoation[]

Guess you like

Origin blog.csdn.net/weixin_49343190/article/details/109168408