Constructor getDeclaredAnnotations() method in Java with Examples
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 no 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
// 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
// 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()
example :
Java
package abc; import java.lang.annotation.*; import java.lang.reflect.*; public class as { @Retention (RetentionPolicy.RUNTIME) @interface MyAnnotation { String value(); } public static class MyClass { @MyAnnotation ( "constructor Annotation" ) public MyClass() { } } public static void main(String[] args) throws Exception { Constructor<?> constructor = MyClass. class .getDeclaredConstructor(); Annotation[] annotations = constructor.getDeclaredAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); } } } |
output :
@abc.as$MyAnnotation("constructor Annotation")
Please Login to comment...