java.lang.reflect.Field.getAnnotation() Method Example



Description

The java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) method returns this element's annotation for the specified type if such an annotation is present, else null.

Declaration

Following is the declaration for java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) method.

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

Parameters

annotationClass − the Class object corresponding to the annotation type.

Returns

this element's annotation for the specified annotation type if present on this element, else null.

Exceptions

NullPointerException − if the given annotation class is null.

Example

The following example shows the usage of java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
      Field field = SampleClass.class.getField("sampleField");
      Annotation annotation = field.getAnnotation(CustomAnnotation.class);
      if(annotation instanceof CustomAnnotation){
         CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
         System.out.println("name: " + customAnnotation.name());
         System.out.println("value: " + customAnnotation.value());
      }
   }
}

@CustomAnnotation(name = "SampleClass",  value = "Sample Class Annotation")
class SampleClass {

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String sampleField;
    
   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   }
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
   public String name();
   public String value();
}

Let us compile and run the above program, this will produce the following result −

name: sampleClassField
value: Sample Field Annotation
java_reflect_field.htm
Advertisements