Wednesday, October 8, 2025
HomeLanguagesJavaField getDeclaredAnnotations() method in Java With Examples

Field getDeclaredAnnotations() method in Java With Examples

The getDeclaredAnnotations() method of java.lang.reflect.Field is used to return annotations that are directly present on this Field object and ignores inherited annotations. If there are no annotations directly present on this element, the return value is an empty array. The caller can modify the returned array as method sent a copy of the actual object; it will have no effect on the arrays returned to other callers. 

Syntax:

public Annotation[] getDeclaredAnnotations()

Parameters: This method accepts nothing. 

Return: This method returns annotations directly present on this element. 

Below programs illustrate getDeclaredAnnotations() method: 

Program 1: 

Java




// 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 getDeclaredAnnotations() method
        Annotation[] annotations
            = field.getDeclaredAnnotations();
 
        // print the results
        System.out.println(
            Arrays
                .toString(annotations));
    }
 
    @Target({ ElementType.TYPE_USE })
    @Retention(RetentionPolicy.RUNTIME)
    private @interface SpecialNumber {
    }
}


Output:

[]

Program 2: 

Java




// 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 getDeclaredAnnotations()
        Annotation[] annotations
            = field.getDeclaredAnnotations();
 
        // print results
        System.out.println(
            Arrays
                .toString(annotations));
    }
}


Output:

[@java.lang.Deprecated()]

References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getDeclaredAnnotations–

RELATED ARTICLES

Most Popular

Dominic
32341 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6709 POSTS0 COMMENTS
Nicole Veronica
11874 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6832 POSTS0 COMMENTS
Ted Musemwa
7092 POSTS0 COMMENTS
Thapelo Manthata
6783 POSTS0 COMMENTS
Umr Jansen
6786 POSTS0 COMMENTS