java.lang.reflect.Method.getDeclaredAnnotations() Method Example



Description

The java.lang.reflect.Method.getDeclaredAnnotations() method returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.Method.getDeclaredAnnotations() method.

public Annotation[] getDeclaredAnnotations()

Returns

All annotations directly present on this element.

Example

The following example shows the usage of java.lang.reflect.Method.getDeclaredAnnotations() method.

Live Demo
package com.tutorialspoint;

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

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

      Method[] methods = SampleClass.class.getMethods();
      Annotation[] annotations = methods[0].getDeclaredAnnotations();
      for(Annotation annotation : annotations){
         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="getSampleMethod",  value = "Sample Method Annotation")
   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: getSampleMethod
value: Sample Method Annotation
java_reflect_method.htm
Advertisements