Java Field getAnnotationsByType()方法实例

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

Java Field getAnnotationsByType()方法实例

java.lang.reflect.FieldgetAnnotationsByType() 方法用于返回与该字段元素相关的注释。这是一个为字段对象获取注释的重要方法。如果没有与这个字段元素相关的注解,则返回空数组。调用者可以修改返回的数组,因为该方法发送的是实际对象的副本;它对返回给其他调用者的数组没有影响。

语法

public <T extends Annotation> T[]   getAnnotationsByType(Class<T> annotationClass)

参数: 该方法接受 annotationClass ,它是与注解类型相对应的Class对象。

返回 :如果与此元素相关,此方法返回此元素的所有指定注释类型的 注释 ,否则返回一个长度为零的数组。

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

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

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

输出:

[@GFG$annotations(value=32512.21)]

程序2

// Java program to illustrate// getAnnotationsByType() method  import java.lang.annotation.*;import java.lang.reflect.Field;import java.util.Arrays;  public class GFG {      // initialize field with    // default value in annotation    @annotations("ChipherCodes@#!")    private double string;      public static void main(String[] args)        throws NoSuchFieldException    {          // create a Field object        Field field            = GFG.class                  .getDeclaredField("string");          // apply getAnnotationsByType()        annotations[] annotations            = field.getAnnotationsByType(                annotations.class);          // print results        System.out.println(            Arrays.toString(                annotations));    }      @Target({ ElementType.FIELD })    @Retention(RetentionPolicy.RUNTIME)    private @interface annotations {        String value();    }}

输出:

[@GFG$annotations(value=ChipherCodes@#!)]

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

相关推荐