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
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String[] args)
{
Class classObj = shape. class ;
Constructor[] cons
= classObj.getConstructors();
Annotation[] annotations
= cons[ 0 ].getDeclaredAnnotations();
System.out.println("Annotation : "
+ annotations);
}
@CustomAnnotation (createValues = "GFG")
public class shape {
@CustomAnnotation (createValues = "GFG")
public shape()
{
}
}
public @interface CustomAnnotation {
public String createValues();
}
}
|
Output:
Annotation : [Ljava.lang.annotation.Annotation;@4aa298b7
Program 2:
Java
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String[] args)
{
Class classObj = String. class ;
Constructor[] cons
= classObj.getConstructors();
Annotation[] annotations
= cons[ 0 ].getDeclaredAnnotations();
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")
Last Updated :
24 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...