Annotation @interface introduction and use

1 Introduction

The annotation @interface is a way to add metadata (metadata) in Java code, which can be used to provide additional information about the program, but it does not directly affect the execution of the program itself. Annotations can be applied to classes, methods, fields, and other program elements to provide additional information about those elements.

Using annotations can provide more flexibility and readability for program writing and processing. They can be used to automatically generate documentation, code analysis, compile-time checking, runtime processing, etc.

To define an annotation, you need to use the @interface keyword and declare properties in the annotation. Annotation properties can be primitive types, strings, enumerations, annotation types or arrays of them. Default values ​​can be provided for annotation attributes using default values.

1.1 Example

Here is an example of defining an annotation:

public @interface MyAnnotation {
    
    
   // 属性声明
   String value() default "default value";
   int number() default 0;
}

In the above example, the @interface keyword defines an annotation named MyAnnotation. Two attributes are declared in the annotation: value and number, and default values ​​are provided for them.

Use the default keyword to set the default value. Variables without default values ​​must be provided when using them. Variables with default values ​​can be set or not set when used.

To use an annotation, use the name of the annotation where appropriate, and provide the value of the attribute. Here are a few examples using annotations:

@MyAnnotation
public class MyClass {
    
    
    @MyAnnotation(number = 10)
    private String myField;

    @MyAnnotation(value = "custom value", number = 20)
    public void myMethod() {
    
    
        // 方法体
    }
}

In the above example, @MyAnnotation is applied to class MyClass, field myField and method myMethod. The value of the annotation property can be set as desired.

At runtime, Java's reflection mechanism can be used to obtain and process annotations. For example, you can check whether a class has a particular annotation applied, or get the value of an annotation's property.

1.2 Detailed explanation

1.2.1 Parameter ElementType in @Target

@Target is a Java annotation meta-annotation (meta-annotation) used to specify the target element type that the annotation can be applied to.

The @Target annotation contains an attribute value that specifies the target element type to which the annotation can be applied. It can accept an array of element types for specifying multiple target element types.

Here are some common target element types:

  • ElementType.TYPE: class, interface or enumeration type
  • ElementType.FIELD: field (including enumeration constants)
  • ElementType.METHOD: method
  • ElementType.PARAMETER: A parameter of a method or constructor
  • ElementType.CONSTRUCTOR: Constructor
  • ElementType.LOCAL_VARIABLE: local variable
  • ElementType.ANNOTATION_TYPE: annotation type
  • ElementType.PACKAGE: 包
  • ElementType.TYPE_PARAMETER: type parameter (Java 8+)
  • ElementType.TYPE_USE: Type usage (Java 8+)

Here is an example to illustrate the use of @Target:

import java.lang.annotation.*;

@Target({
    
    ElementType.TYPE, ElementType.METHOD})
@interface MyAnnotation {
    
    
    String value();
}

@MyAnnotation("Example annotation")
public class MyClass {
    
    
    @MyAnnotation("Example annotation")
    public void myMethod() {
    
    
        // 方法的内容
    }
}

In the above example, we defined a custom annotation MyAnnotation and marked it as @Target({ElementType.TYPE, ElementType.METHOD}), which specifies that the annotation can be applied to classes and methods. Then, the MyAnnotation annotation is applied on the MyClass class and the myMethod method.

This means we can only apply the MyAnnotation annotation to classes and methods, not to other types of elements.

In summary, @Target is a Java annotation meta-annotation that specifies the target element type that the annotation can be applied to. Through the value attribute of @Target, you can specify the target element type that the annotation can be applied to, such as classes, fields, methods, parameters, etc. This helps to limit the scope of the annotation, ensuring it can only be applied to the appropriate element.

1.2.2 RetentionPolicy of @Retention parameter

@Retention is a Java annotation meta-annotation (meta-annotation) used to specify the retention policy of the annotation (retention policy). A retention policy defines when annotations are valid and when they are discarded.

The @Retention annotation contains an attribute value that specifies the retention policy for the annotation. It can have three predefined values:

  • RetentionPolicy.SOURCE: The annotation is only retained in the source code stage, and the annotation is not included in the compiled bytecode. Information about this annotation cannot be obtained at runtime. This retention policy is mainly used for static checking and analysis at compile time, and has no effect on the running of the program.
  • RetentionPolicy.CLASS: The annotation is retained at compile time and included in the compiled bytecode, but the information of the annotation cannot be obtained at runtime. This is the default retention policy, which is used if no retention policy is explicitly specified on the annotation.
  • RetentionPolicy.RUNTIME: The annotation is retained at compile time, and the information of the annotation can be obtained through the reflection mechanism at runtime. This retention policy allows annotations to be processed at runtime and is used to implement custom annotation processors, frameworks, and other runtime behavior.

Here is an example to illustrate the use of @Retention:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    
    
    String value();
}

@MyAnnotation("Example annotation")
public class MyClass {
    
    
    // 类的内容
}

In the above example, we defined a custom annotation MyAnnotation and marked it as @Retention(RetentionPolicy.RUNTIME), which means that the retention policy is specified as runtime retention. Then, the MyAnnotation annotation is applied on the MyClass class.

At runtime, you can use the reflection mechanism to obtain the annotation information of the MyClass class, including the attribute values ​​of the annotation. This is because we specified @Retention(RetentionPolicy.RUNTIME), so that the annotation is retained at compile time and can be obtained at runtime.

In summary, @Retention is a Java annotation meta-annotation used to specify the retention policy of annotations. Through the value attribute of @Retention, you can specify the annotation retention policy as SOURCE, CLASS or RUNTIME. Retention policies determine when annotations are valid and discarded.

1.2.3 @Inherited

@Inherited is a Java annotation meta-annotation (meta-annotation) used to indicate whether an annotation can be inherited. When an annotation is marked @Inherited, it can be inherited by subclasses.

Specifically, if an annotation marked @Inherited is applied to a parent class, then when a subclass of the parent class does not explicitly use the same annotation, the subclass will inherit the annotation of the parent class. This means that subclasses are also considered to have the same annotation.

It should be noted that @Inherited is only valid for class inheritance, not for interface inheritance.

Here is an example to illustrate the use of @Inherited:

import java.lang.annotation.*;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    
    
    String value();
}

@MyAnnotation("Parent Annotation")
class ParentClass {
    
    
}

class ChildClass extends ParentClass {
    
    
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        ParentClass parent = new ParentClass();
        ChildClass child = new ChildClass();

        // 检查父类是否具有 MyAnnotation 注解
        MyAnnotation parentAnnotation = parent.getClass().getAnnotation(MyAnnotation.class);
        System.out.println("Parent Annotation: " + parentAnnotation);

        // 检查子类是否具有 MyAnnotation 注解
        MyAnnotation childAnnotation = child.getClass().getAnnotation(MyAnnotation.class);
        System.out.println("Child Annotation: " + childAnnotation);
    }
}

In the above example, we defined a custom annotation MyAnnotation and marked it as @Inherited. Then, the MyAnnotation annotation is applied on the ParentClass. Next, we create an instance of ChildClass.

At runtime, we get the annotations of ParentClass and ChildClass through reflection, and print out the values ​​of the annotations. Since MyAnnotation is marked @Inherited, ChildClass inherits the annotation of ParentClass, so it is also considered to have the same annotation.
The output will be:

Parent Annotation: @MyAnnotation(value=Parent Annotation)
Child Annotation: @MyAnnotation(value=Parent Annotation)

It can be seen that the subclass ChildClass inherits the annotations of the parent class ParentClass.

In summary, @Inherited is a Java annotation meta-annotation used to indicate whether an annotation can be inherited. When an annotation is marked @Inherited, it can be inherited by subclasses.

1.2.4 @Documented

@Documented is a Java annotation meta-annotation (meta-annotation) used to indicate whether the annotated element is included in the API documentation.

When an annotation is marked with @Documented, its information will be included in the generated API documentation. In this way, programmers who use the annotation can see the description and usage of the annotation in the document, so as to better understand and use the annotated element.

It should be noted that @Documented is only used to indicate whether the annotation itself is included in the API documentation, and does not affect whether the element to which the annotation is applied is included in the documentation.

Here is an example to illustrate the use of @Documented:

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    
    
    String value();
}

@MyAnnotation("This is a documented annotation.")
public class MyClass {
    
    
    // 类的内容
}

In the above example, we defined a custom annotation MyAnnotation and marked it as @Documented. Then, the MyAnnotation annotation is applied on the MyClass class.

When we generate API documentation, whether using a tool such as Javadoc or an integrated development environment (IDE), the documentation includes annotation information about the annotated element (in this case the class MyClass). This way, other developers can get instructions for and how to use the annotation when viewing the documentation.

In summary, @Documented is a Java annotation meta-annotation used to indicate whether the annotated element is included in the API documentation. When an annotation is marked with @Documented, its information will be included in the generated API documentation for other developers to view.

Guess you like

Origin blog.csdn.net/weixin_44727769/article/details/130871806