Field getAnnotationsByType() method in Java With Examples
Last Updated :
17 Sep, 2019
The getAnnotationsByType() method of java.lang.reflect.Field is used to return annotations that are associated with this field element. This is an important method to get annotation for Field object. If there are no annotations associated with this Field element, the return empty array. The caller can modify the returned array as method sent a copy of the actual object; it will have no effect on the arrays returned to other callers.
Syntax:
public <T extends Annotation> T[]
getAnnotationsByType(Class<T> annotationClass)
Parameters: This method accepts annotationClass which is the Class object corresponding to the annotation type.
Return: This method returns all this element’s annotations for the specified annotation type if associated with this element, else an array of length zero.
Exception: This method throws NullPointerException if the given annotation class is null.
Below programs illustrate getAnnotationsByType() method:
Program 1:
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GFG {
@annotations ( 32512.21 )
private double realNumbers;
public static void main(String[] args)
throws NoSuchFieldException
{
Field field
= GFG. class
.getDeclaredField( "realNumbers" );
annotations[] annotations
= field.getAnnotationsByType(
annotations. class );
System.out.println(
Arrays
.toString(annotations));
}
@Target ({ ElementType.FIELD })
@Retention (RetentionPolicy.RUNTIME)
private @interface annotations {
double value() default 99.9 ;
}
}
|
Output:
[@GFG$annotations(value=32512.21)]
Program 2:
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GFG {
@annotations ( "ChipherCodes@#!" )
private double string;
public static void main(String[] args)
throws NoSuchFieldException
{
Field field
= GFG. class
.getDeclaredField( "string" );
annotations[] annotations
= field.getAnnotationsByType(
annotations. class );
System.out.println(
Arrays.toString(
annotations));
}
@Target ({ ElementType.FIELD })
@Retention (RetentionPolicy.RUNTIME)
private @interface annotations {
String value();
}
}
|
Output:
[@GFG$annotations(value=ChipherCodes@#!)]
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotationsByType-java.lang.Class-
Share your thoughts in the comments
Please Login to comment...