Constructor getAnnotation() method in Java with Examples
Last Updated :
27 Nov, 2019
The getAnnotation() method of a Constructor class is used to get this constructor object annotation for the specified type if such an annotation is present, else null. Specified type is passed as parameter.
Syntax:
public <T extends Annotation> T
getAnnotation(Class<T> annotationClass)
Parameters: This method accepts a single parameter annotationClass which represents the Class object corresponding to the annotation type.
Return value: This method returns this element’s annotation for the specified annotation type if present on this element, else null.
Exception: This method throws NullPointerException if the given annotation class is null.
Below programs illustrate the getAnnotation() method:
Program 1:
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String... args)
throws NoSuchMethodException
{
Constructor[] constructors
= Demo. class .getConstructors();
Annotation annotation
= constructors[ 0 ]
.getAnnotation(PathVar. class );
if (annotation instanceof PathVar) {
PathVar customAnnotation
= (PathVar)annotation;
System.out.println(
"Path: "
+ customAnnotation.Path());
}
}
}
class Demo {
public Demo( @PathVar (Path = "Demo/usr" )
String str) {}
}
@Target ({ ElementType.TYPE_USE })
@Retention (RetentionPolicy.RUNTIME)
@interface PathVar {
public String Path();
}
|
Output:
Path: Demo/usr
Program 2:
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String... args)
throws NoSuchMethodException
{
Constructor[] constructors
= Maths. class .getConstructors();
Annotation annotation
= constructors[ 0 ]
.getAnnotation(Calculator. class );
System.out.println(
"Annotation:"
+ annotation.toString());
}
}
@Calculator (add = "Adding value" ,
subtract = "Subtracting Value" )
class Maths {
@Calculator (add = "Adding value" ,
subtract = "Subtracting Value" )
public Maths() {}
}
@Retention (RetentionPolicy.RUNTIME)
@interface Calculator {
public String add();
public String subtract();
}
|
Output:
Annotation : @Calculator(add=Adding value, subtract=Subtracting Value)
References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getAnnotation(java.lang.Class)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...