Java Field getAnnotatedType()方法及示例

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

Java Field getAnnotatedType()方法及示例

java.lang.reflect.FieldgetAnnotatedType() 方法用于返回一个annonatedType对象,该对象表示使用一个类型来指定该字段的声明类型。类的每个字段都是由一些AnnotatedType声明的。AnnotatedType代表任何类型的潜在注释使用,包括数组类型、参数化类型、类型变量或当前在Java虚拟机中运行的通配符类型。返回的 AnnotatedType 实例可以是 AnnotatedType 本身的实现或其子接口之一的实现。AnnotatedArrayType、AnnotatedParameterizedType、AnnotatedTypeVariable、AnnotatedWildcardType。

语法

public AnnotatedType getAnnotatedType()

参数: 该方法不接受任何东西。
返回 :该方法返回一个代表该字段所代表的声明类型的 对象 。下面的程序说明了getAnnotatedType()方法。

程序1 :

// Java program to illustrate// getAnnotatedType() method import java.lang.reflect.AnnotatedType;import java.lang.reflect.Field;import java.util.Arrays; public class GFG {     private int number;     public static void main(String[] args)        throws NoSuchFieldException    {         // get Field object        Field field            = GFG.class                  .getDeclaredField("number");         // apply getAnnotatedType() method        AnnotatedType annotatedType            = field.getAnnotatedType();         // print the results        System.out.println(            "Type: "            + annotatedType                  .getType()                  .getTypeName());        System.out.println(            "Annotations: "            + Arrays                  .toString(                      annotatedType                          .getAnnotations()));    }}

输出

Type: intAnnotations: []

程序2

// Java Program to illustrate// getAnnotatedType() method import java.lang.annotation.*;import java.lang.reflect.*;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 getAnnotatedType() method        AnnotatedType annotatedType            = field.getAnnotatedType();         // 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 {    }}

输出

Type: int[]Annotations: [@GFGSpecialNumber()]Declared Annotations: [@GFGSpecialNumber()]

参考文献 : https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotatedType-

相关推荐