Obtaining All Annotations: getAnnotations( ) : Annotations Reflection « Language « Java Tutorial






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

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

  int intValue();
}

@Retention(RetentionPolicy.RUNTIME)
@interface What {
  String description();
}

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

  public static void main(String[] arg) {
    try {
      MainClass ob = new MainClass();
      Annotation[] annos = ob.getClass().getAnnotations();
      
      System.out.println("All annotations for Meta2:");
      for(Annotation a : annos)
        System.out.println(a);
      
    } catch (Exception exc) {
    }
  }
}
All annotations for Meta2:
@MyAnnotation(stringValue=for class, intValue=100)
@What(description=An annotation test class)








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