Java Field getDeclaredAnnotations()方法实例

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

Java Field getDeclaredAnnotations()方法实例

java.lang.reflect.FieldgetDeclaredAnnotations() 方法用于返回直接存在于这个Field对象上的注释,而忽略继承的注释。如果这个元素上没有直接存在的注解,返回值是一个空数组。调用者可以修改返回的数组,因为方法发送的是实际对象的副本;它对返回给其他调用者的数组没有影响。
语法

public Annotation[] getDeclaredAnnotations()

参数: 该方法不接受任何东西。
返回 :该方法返回直接存在于该元素上的 注释 。以下程序说明了getDeclaredAnnotations()方法:
程序1 :

// Java program to illustrate// getDeclaredAnnotations() method import java.lang.annotation.*;import java.lang.reflect.Field;import java.util.Arrays; public class GFG {     // initialize field with  annotation    private int @SpecialNumber[] number;     public static void main(String[] args)        throws NoSuchFieldException    {        // get Field object        Field field            = GFG.class.getDeclaredField("number");         // apply getAnnotatedType() method        Annotation[] annotations            = field.getDeclaredAnnotations();         // print the results        System.out.println(            Arrays                .toString(annotations));    }     @Target({ ElementType.TYPE_USE })    @Retention(RetentionPolicy.RUNTIME)    private @interface SpecialNumber {    }}

输出

[]

程序2

// Java program to illustrate// getDeclaredAnnotations() method import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.util.Arrays; public class GFG {     // initialize field with  annotation    @Deprecated    private String string        = " Welcome to GeeksForGeeks";     public static void main(String[] args)        throws NoSuchFieldException    {         // create Field object        Field field            = GFG.class                  .getDeclaredField("string");         // apply getAnnotation()        Annotation[] annotations            = field.getDeclaredAnnotations();         // print results        System.out.println(            Arrays                .toString(annotations));    }}

输出

[@java.lang.Deprecated()]

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

相关推荐