Java Annotation reflection at run time

Introduction

Here is a program uses reflection to display the annotation associated with a method:

The code uses reflection to get and display the values of str and val in the MyAnno annotation associated with myMeth().


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

// An annotation type declaration. 
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();//from   w  ww. j  a va 2  s  .c  om

  int val();
}

public class Main {
  // Annotate a method.
  @MyAnno(str = "Annotation Example", val = 100)
  public static void myMethod() {
    Main ob = new Main();

    // Obtain the annotation for this method
    // and display the values of the members.
    try {
      // First, get a Class object that represents
      // this class.
      Class<?> c = ob.getClass();

      // Now, get a Method object that represents
      // this method.
      Method m = c.getMethod("myMethod");

      // Next, get the annotation for this class.
      MyAnno anno = m.getAnnotation(MyAnno.class);

      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMethod();
  }
}



PreviousNext

Related