Close

Java Reflection - Field.getAnnotation() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Field

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Fieldjava.lang.reflect.Fieldjava.lang.reflect.MemberMemberLogicBig

Method:

public <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Returns this field's annotation for the specified type if such an annotation is present, else null.

Note that this method is defined in AnnotatedElement interface.


Examples


package com.logicbig.example.field;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

public class GetAnnotationExample {
@PrimeNumber
private int anInt;

public static void main(String... args) throws NoSuchFieldException {
Field field = GetAnnotationExample.class.getDeclaredField("anInt");
PrimeNumber annotation = field.getAnnotation(PrimeNumber.class);
System.out.println(annotation);
}

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
private @interface PrimeNumber {}
}

Output

@com.logicbig.example.field.GetAnnotationExample$PrimeNumber()




See Also