Java Annotation create repeating annotations

Introduction

Java annotation can be repeated on the same element.

To be a repeatable annotation, annotated with the @Repeatable annotation in java.lang.annotation.

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

// Make MyAnno repeatable
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyRepeatedAnnos.class)
@interface MyAnno {
  String str() default "Testing";

  int val() default 999;
}

// This is the container annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyRepeatedAnnos {
  MyAnno[] value();//  w w  w. j  a v  a2 s .c o  m
}

public class Main {

  // Repeat MyAnno on myMethod().
  @MyAnno(str = "First annotation", val = -1)
  @MyAnno(str = "Second annotation", val = 100)
  public static void myMethod(String str, int i) {
    Main ob = new Main();

    try {
      Class<?> c = ob.getClass();

      // Obtain the annotations for myMethod().
      Method m = c.getMethod("myMethod", String.class, int.class);

      // Display the repeated MyAnno annotations.
      Annotation anno = m.getAnnotation(MyRepeatedAnnos.class);
      System.out.println(anno);


      Annotation[] annos = m.getAnnotationsByType(MyAnno.class);  
      for(Annotation a : annos)  {
        System.out.println(a); 
      }
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMethod("test", 10);
  }
}



PreviousNext

Related