AnnotationUtil

Introduction

A utility class that encapsulates methods related to annotation retrieval.

Usage

Method Introduction

  1. Annotation Retrieval Related Methods:
  • getAnnotations retrieves a list of annotations on a specified class, method, field, constructor, etc.
  • getAnnotation retrieves an annotation of a specified type
  • getAnnotationValue retrieves the value of a specified annotation attribute

Example: We define an annotation:

// The Retention annotation determines the lifecycle of the MyAnnotation annotation
@Retention(RetentionPolicy.RUNTIME)
// The Target annotation determines on which elements the MyAnnotation annotation can be added, such as on a class, property, method, etc.
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface AnnotationForTest {
    /**
     * The default attribute value of the annotation
     * 
     * @return The attribute value
     */
    String value();
}

Add the annotation to the required class:

@AnnotationForTest("test")
public static class ClassWithAnnotation{
}

Retrieve the value in the annotation:

// value is "test"
Object value = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest.class);
  1. Annotation Attribute Retrieval Related Methods:
  • getRetentionPolicy retrieves the retention time of the annotation class, with optional values of SOURCE (source code), CLASS (compilation time), and RUNTIME (runtime), with a default of CLASS.
  • getTargetType retrieves the program elements that the annotation class can be used to modify, such as TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER, etc.
  • isDocumented indicates whether it will be saved in the Javadoc documentation
  • isInherited indicates whether it can be inherited, with a default of false. For more methods, refer to the API documentation: https://apidoc.gitee.com/loolly/hutool/cn/hutool/core/annotation/AnnotationUtil.html