Obtaining Annotations at Run Time by Use of Reflection(通过反射获取注释的值

 

 

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() {
  }

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

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

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

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

  }
}
 

你可能感兴趣的:(java,C++,c,C#)