Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Constructor getDeclaredAnnotations() method in Java with Examples

  • Last Updated : 03 Nov, 2021

The getDeclaredAnnotations() method of java.lang.reflect.Constructor class is used to return annotations present on this Constructor element as an array of Annotation class objects. The getDeclaredAnnotations() method ignores inherited annotations on this constructor object.Returned array can contains no annotations means length of that array can be 0 if the constructor has nop annotations.

Syntax:

public Annotation[] getDeclaredAnnotations()

Parameters: This method accepts nothing.

Return: This method returns array of annotations directly present on this element

Below programs illustrate getDeclaredAnnotations() method:
Program 1:




// Java program to illustrate
// getDeclaredAnnotations() method
  
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create a class object
        Class classObj = shape.class;
  
        // get Constructor object
        // array from class object
        Constructor[] cons
            = classObj.getConstructors();
  
        // get array of annotations
        Annotation[] annotations
            = cons[0].getDeclaredAnnotations();
  
        // print length of annotations array
        System.out.println("Annotation : "
                           + annotations);
    }
  
    @CustomAnnotation(createValues = "GFG")
    public class shape {
  
        @CustomAnnotation(createValues = "GFG")
        public shape()
        {
        }
    }
  
    // create a custom annotation
    public @interface CustomAnnotation {
        public String createValues();
    }
    }
Output:
Annotation : [Ljava.lang.annotation.Annotation;@4aa298b7

Program 2:




// Java program to illustrate
// getDeclaredAnnotations() method
  
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create a class object
        Class classObj = String.class;
  
        // get Constructor object
        // array from class object
        Constructor[] cons
            = classObj.getConstructors();
  
        // get array of annotations
        Annotation[] annotations
            = cons[0].getDeclaredAnnotations();
  
        // print length of annotations array
        System.out.println("Annotation length : "
                           + annotations.length);
    }
}
Output:
Annotation length : 0

References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getDeclaredAnnotations()


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!