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

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

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

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

句法:

public AnnotatedType getAnnotatedType()

参数:此方法不接受任何内容。

Return :此方法返回一个对象,该对象表示该字段表示的字段的声明类型。

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

// 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: int
Annotations: []

方案二:

// 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: [@GFG$SpecialNumber()]
Declared Annotations: [@GFG$SpecialNumber()]

参考资料: https: Java/lang/reflect/Field.html#getAnnotatedType–