Reflection: getMethod( ) with parameters : Annotations Reflection « Language « Java Tutorial






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

// A simple annotation type.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue();

  int intValue();
}

public class MainClass {
  // Annotate a method.
  @MyAnnotation(stringValue = "Annotation Example", intValue = 100)
  public static void myMethod(String str, int i) {
  }

  public static void main(String[] a) {
    try {
      MainClass ob = new MainClass();
      Class c = ob.getClass();

      Method m = c.getMethod("myMethod", String.class, int.class);

      MyAnnotation anno = m.getAnnotation(MyAnnotation.class);

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

  }
}
Annotation Example 100








1.12.Annotations Reflection
1.12.1.Obtaining Annotations at Run Time by Use of Reflection
1.12.2.Reflection: getMethod( ) with parameters
1.12.3.Obtaining All Annotations: getAnnotations( )
1.12.4.Getting all annotations for a method