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



Description

The java.lang.reflect.Constructor.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.Constructor.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.Constructor.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.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {

      Constructor[] constructors = SampleClass.class.getConstructors();

      Annotation annotation = constructors[0].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 {
   private String sampleField;

   @CustomAnnotation(name="sampleClassConstructor",  value = "Sample Constructor Annotation")
   public SampleClass(){
   }

   public SampleClass(String sampleField){
      this.sampleField = 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: sampleClassConstructor
value: Sample Constructor Annotation
java_reflect_constructor.htm
Advertisements