Field getAnnotation() method in Java With Examples
Last Updated :
14 Apr, 2023
The getAnnotation() method of java.lang.reflect.Field is used to return returns Field objects for the specified type if such an annotation is present, else null.This is important method to get annotation for Field object. Syntax:
public <T extends Annotation> T
getAnnotation(Class<T> annotationClass)
Parameters: This method annotationClass which is the Class object corresponding to the annotation type. Return: 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 getAnnotation() method: Program 1:
Java
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GFG {
@annotations ( 3125462345.32155365326 )
private double realNumbers;
public static void main(String[] args)
throws NoSuchFieldException
{
Field field
= GFG. class
.getDeclaredField("realNumbers");
annotations annotations
= field.getAnnotation(
annotations. class );
System.out.println(annotations);
}
@Target ({ ElementType.FIELD })
@Retention (RetentionPolicy.RUNTIME)
private @interface annotations {
double value() default 99.9 ;
}
}
|
Output:
@GFG$annotations(value=3.1254623453215537E9)
Program 2:
Java
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GFG {
private int @SpecialNumber [] number;
public static void main(String[] args)
throws NoSuchFieldException
{
Field field
= GFG. class
.getDeclaredField("number");
AnnotatedType annotatedType
= field.getAnnotation();
System.out.println(
"Type: "
+ annotatedType.getType()
.getTypeName());
System.out.println(
"Annotations: "
+ Arrays.toString(
annotatedType
.getAnnotations()));
System.out.println(
"Declared Annotations: "
+ Arrays.toString(
annotatedType
.getDeclaredAnnotations()));
}
@Target ({ ElementType.TYPE_USE })
@Retention (RetentionPolicy.RUNTIME)
private @interface SpecialNumber {
}
}
|
Output:
@GFG$annotations(value=WelcomeTOGFG)
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotation–
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...