Java annotations, meta annotations, use of custom annotations

Java annotations

Starting from JDK5, Java has added support for metadata, that is, annotations. There is a certain difference between annotations and annotations. Annotations can be understood as special tags in the code. These tags can be read during compilation, class loading, and runtime. , and perform corresponding processing . Through annotations, developers can embed supplementary information in source code without changing the original code and logic .

Annotation (Annotation) can be regarded as an extended template for a class/method. Each class/method annotates different parameters for the class/method according to the rules in the annotation class, and different parameters can be obtained where it is used. Various parameters and values ​​​​annotated in classes/methods

basic annotation

Java provides five basic annotations, namely@Override,@Deprecated,@SuppressWarnings,@SafeVarargs,@FunctionalInterface

1.@Override

Limit the parent class override method: @Override, when the subclass overrides the parent class method, the subclass can add this annotation, and when the subclass overrides the parent class method, the subclass can add this annotation.

2.@Deprecated

Marked obsolete: @Deprecated, this annotation is used to indicate that a program element class, method, etc. are outdated, and the compiler will give a warning when other programs use outdated classes and methods ( xxx )

3.@SuppressWarnings

Suppress compiler warnings: @SuppressWarnings, the element modified by this annotation and all sub-elements of the element cancel the display of compiler warnings

4.@SafeVarargs

"Heap pollution" warning with @SafeVarargs

5.@FunctionalInterface

Functional interface and @Functionallnterface, this annotation ensures that the interface has only one abstract method, note that this can only modify the interface.

Functional interface: If there is only one abstract method in the interface (it can contain multiple default methods or multiple static methods),
only constant fields and abstract methods can be declared in the interface body, and they are implicitly declared as public, static, and final.
Interfaces cannot have private methods or variables.

Meta annotations provided by Java

The role of meta-annotations is to annotate other annotations to provide explanations for other annotation types.

1.@Retention

@Retention is used to modify the definition of the annotation. Its function is how long the modified annotation can be saved (that is, the life cycle of the annotation) . This annotation needs to use parameters (the parameters can be SOURCE, CLASS, RUNTIME ).

@Retention source code:

package java.lang.annotation;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    
    
    RetentionPolicy value();
}

@Retention annotation parameter is an enumeration type, as follows

package java.lang.annotation;

public enum RetentionPolicy {
    
    
    SOURCE,
    CLASS,
    RUNTIME
}

RetentionPolicy.CLASS (default value) The compiler records the annotation in the class file. When running a java program, the JVM cannot obtain annotation information.

The RetentionPolicy.RUNTIME compiler records this annotation in the class file. When running a java program, the JVM can obtain annotation information, and the program can obtain the annotation information through reflection

RetentionPolicy.SOURCE The annotation is only saved in the source code, and the compiler discards the annotation directly.

2.@Target

The @Target annotation is used to describe the usage scope of the annotation, that is, where the annotation can be used (TYPE class|interface, FIELD field, METHOD method, PARAMETER parameter...), and its usage scope is also an enumeration array ElementType[] value();.

@Target annotation defines source code:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    
    
    ElementType[] value();
}

ElementType[] parameter array source code of @Target annotation:

package java.lang.annotation;

public enum ElementType {
    
    
    TYPE,
    FIELD,
    METHOD,
    PARAMETER,
    CONSTRUCTOR,
    LOCAL_VARIABLE,
    ANNOTATION_TYPE,
    PACKAGE,
    TYPE_PARAMETER,
    TYPE_USE
}

value Annotation use range
METHOD can be used in the method
TYPE Can be used on classes or interfaces
ANNOTATION_TYPE Can be used on annotation types (types modified by @interface)
CONSTRUCTOR Can be used in constructor
FIELD available on field
LOCAL_VARIABLE can be used on local variables
PACKAGE Used to record package information of java files
PARAMETER can be used on parameters

3.@Documented

The @Documented annotation is used to specify that the modified annotation class will be extracted into a document by the javadoc tool. If this annotation modification is used when defining the annotation class, all programmers and API documents decorated with this annotation will contain the annotation description.

package java.lang.annotation;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
    
    
}

4.@Inherited

The @Inherited annotation specifies that the annotation modified by it will be inherited, that is, the subclass can inherit the annotation in the parent class

package java.lang.annotation;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
    
    
}

custom annotation

Custom annotations need to be @interfacedefined. When using @interface custom annotations, they are automatically inherited java.lang.annotation.Annotation接口.

Custom comment format:

权限修饰符 @interface 注解名{
    
    
	// 定义内容
	String value() default "";
	// 参数类型 参数名 默认值 ;
	.....
}
  • @interface is used to declare an annotation
  • The above String value();indicates that this annotation needs to provide a String type parameter, and its default value is an empty stringdefault ""
  • value() is the name of the parameter
  • String is the required type of the parameter, and the parameter type can only be the basic type (Class, String, enum)
  • The default value of the parameter can be declared by default
  • If there is only one parameter member, the general parameter name is value (of course, the parameter name can be customized, it is just a habit)
  • Annotation elements must require a value. When defining annotation elements, empty strings are often used, with 0 as the default value

Use of custom annotations

package com.robin.annotation;

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

// 使用自定义的注解 传入参数 robin 和 23
@MyAnnotation(value = "robin", age = 23)
public class AnnoTest01 {
    
    


    // 使用自定义的注解 传入参数 知更鸟 和 18
    @MyAnnotation(value = "知更鸟",age = 18)
    public void test01() {
    
    

    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
    
    
        // 通过反射来获取当前Class类对象中的注解
        Class<?> cls = Class.forName("com.robin.annotation.AnnoTest01");// 获取AnnoTest01的Class类对象
        MyAnnotation annotation1 = cls.getAnnotation(MyAnnotation.class);// 获取当前Class类对象的注解信息
        System.out.println("作用在类上的注解:"+annotation1);// @com.robin.annotation.MyAnnotation(value=robin, age=23)
        // 通过Class类对象获取Method对象
        Method test01 = cls.getMethod("test01");
        MyAnnotation annotation2 = test01.getAnnotation(MyAnnotation.class);
        System.out.println("作用在method上的注解:"+annotation2);// @com.robin.annotation.MyAnnotation(value=知更鸟, age=18)

    }

}

// 自定义内部类注解
@Target({
    
    ElementType.TYPE, ElementType.METHOD})// 作用范围为类和方法上面
@Retention(RetentionPolicy.RUNTIME)// 此注解的生命周期为RUNTIME
@interface MyAnnotation {
    
    
    String value() default "";

    int age() default 0;
}

insert image description here


Happy New Years Eve everyone!

Guess you like

Origin blog.csdn.net/m0_63622279/article/details/128746874