📜  Java中的字段 getAnnotation() 方法及示例

📅  最后修改于: 2022-05-13 01:55:42.449000             🧑  作者: Mango

Java中的字段 getAnnotation() 方法及示例

Java.lang.reflect.FieldgetAnnotation()方法用于返回返回指定类型的Field 对象,如果存在这样的注解,否则为null。这是获取Field 对象注解的重要方法。

句法:

public  T
  getAnnotation(Class annotationClass)

参数:该方法annotationClass是注解类型对应的Class对象。

返回:此方法返回此元素的指定注释类型的注释(如果存在于此元素上),否则返回 null。

异常:如果给定的注释类为空,此方法将抛出NullPointerException

下面的程序说明了 getAnnotation() 方法:
方案一:

// Java program to illustrate
// getAnnotation() method
  
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.util.Arrays;
  
public class GFG {
  
    // initialize field with
    // default value in annotation
    @annotations(3125462345.32155365326)
  
    private double realNumbers;
  
    public static void main(String[] args)
        throws NoSuchFieldException
    {
  
        // create Field object
        Field field
            = GFG.class
                  .getDeclaredField("realNumbers");
  
        // apply getAnnotation()
        annotations annotations
            = field.getAnnotation(
                annotations.class);
  
        // print results
        System.out.println(annotations);
    }
  
    @Target({ ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    private @interface annotations {
        double value() default 99.9;
    }
}
输出:
@GFG$annotations(value=3.1254623453215537E9)

方案二:

// Java program to illustrate
// getAnnotation() method
  
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.util.Arrays;
  
public class GFG {
    private int @SpecialNumber[] number;
  
    public static void main(String[] args)
        throws NoSuchFieldException
    {
        // get Field object
        Field field
            = GFG.class
                  .getDeclaredField("number");
  
        // apply getAnnotation() method
        AnnotatedType annotatedType
            = field.getAnnotation();
  
        // print the results
        System.out.println(
            "Type: "
            + annotatedType.getType()
                  .getTypeName());
        System.out.println(
            "Annotations: "
            + Arrays.toString(
                  annotatedType
                      .getAnnotations()));
        System.out.println(
            "Declared Annotations: "
            + Arrays.toString(
                  annotatedType
                      .getDeclaredAnnotations()));
    }
  
    @Target({ ElementType.TYPE_USE })
    @Retention(RetentionPolicy.RUNTIME)
    private @interface SpecialNumber {
    }
}
输出:
@GFG$annotations(value=WelcomeTOGFG)

参考文献: https: Java/lang/reflect/Field.html#getAnnotation–