Uses reflection to display the annotation associated with a method. : Annotation « Reflection « Java






Uses reflection to display the annotation associated with a method.

   

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

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

class Meta {

  @MyAnno(str = "Annotation Example", val = 100)
  public static void myMeth() {
    Meta ob = new Meta();

    try {
      Class c = ob.getClass();

      Method m = c.getMethod("myMeth");

      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[]) {
    myMeth();
  }
}

   
    
  








Related examples in the same category

1.Get annotation by annotation class
2.Show all annotations for a class and a method.
3.default values in an annotation.
4.Does a method have an annotation
5.Get Annotation Parameter
6.A better concise toString method for annotation types
7.Find Annotated Method
8.Find Annotated Fields
9.Get default annotation value
10.Get annotation value
11.Is Field Annotation Present
12.Get Annotated Declared Fields