Java Field getAnnotation()方法及示例

来源:这里教程网 时间:2026-02-17 20:50:38 作者:

Java Field getAnnotation()方法及示例

java.lang.reflect.FieldgetAnnotation() 方法用于返回指定类型的Field对象的注释,如果存在这样的注释,则返回null。

语法

public <T extends Annotation> T  getAnnotation(Class<T> annotationClass)

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

返回 :如果该元素上存在指定的注释类型,该方法返回该元素的 注释 ,否则为空。

异常 :如果给定的注释类是空的,这个方法会抛出 NullPointerException

以下程序说明了getAnnotation()方法:
程序1 :

// 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)

程序2

// 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://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotation-

相关推荐