@Target

@Target is an annotation in Java that is used to specify the scope of application of the annotation. It can be used in the definition of the annotation to limit the target elements to which the annotation can be applied.

The @Target configuration is a meta-annotation used to annotate other annotations. It has the following configurations:

  1. ElementType.ANNOTATION_TYPE: Can be applied to other annotations. This means that the annotated element is an annotation.
  2. ElementType.CONSTRUCTOR: Can be applied to constructors.
  3. ElementType.FIELD: Can be applied to fields.
  4. ElementType.LOCAL_VARIABLE: Can be applied to local variables.
  5. ElementType.METHOD: Can be applied to methods.
  6. ElementType.MODULE: Can be applied to modules (new in Java 9).
  7. ElementType.PACKAGE: Can be applied to packages.
  8. ElementType.PARAMETER: Can be applied to the parameters of the method.
  9. ElementType.TYPE: Can be applied to classes, interfaces, enumerations, and annotation types.
  10. ElementType.TYPE_PARAMETER: Can be applied to type parameters (new in Java 8).
  11. ElementType.TYPE_USE: Can be applied to type usage (new in Java 8).

Each configuration item corresponds to a different element in Java, and the @Target annotation can limit the target range to which the annotation can be applied. For example, if the @Target configuration of an annotation is ElementType.METHOD, then the annotation can only be applied to the method and cannot be applied elsewhere.

The following is a sample code showing how to use the @Target annotation to limit the scope of the annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({
    
    ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    
    
    // 注解的定义
}

@MyAnnotation
public class MyClass {
    
    
    @MyAnnotation
    public void myMethod() {
    
    
        // 方法体
    }
}

In the above example, the @Target configuration of the @MyAnnotation annotation is ElementType.TYPE and ElementType.METHOD, indicating that the annotation can be applied to classes and methods. Therefore, both the MyClass class and the myMethod() method can be annotated with @MyAnnotation.

This is all the configuration items of @Target. By selecting the applicable configuration items reasonably, the annotation can be limited to a specific target element to improve the readability and maintainability of the code.

Guess you like

Origin blog.csdn.net/qq_41177135/article/details/132027071