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 annottaions 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(); } } |
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); } } |
Annotation length : 0
References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getDeclaredAnnotations()
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.