Java Annotation reflection

In this chapter you will learn:

  1. How to get all annotations
  2. Syntax for Java Annotation reflection
  3. Example - Java Annotation reflection

Description

You can obtain all annotations that have RUNTIME retention that are associated with an item by calling getAnnotations( ) on that item.

Syntax

It has this general form:


Annotation[ ] getAnnotations( )

Example


import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
/*from   w  w  w.  jav a 2 s .c o m*/
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

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

@What(description = "An annotation")
@MyAnno(str = "Meta2", val = 99)
public class Main {
  @What(description = "test method")
  @MyAnno(str = "Testing", val = 100)
  public static void myMeth() throws Exception {
    Main ob = new Main();
    Annotation annos[] = ob.getClass().getAnnotations();
    System.out.println("All annotations for Meta2:");
    for (Annotation a : annos) {
      System.out.println(a);
    }
    Method m = ob.getClass().getMethod("myMeth");
    annos = m.getAnnotations();
    for (Annotation a : annos) {
      System.out.println(a);
    }

  }

  public static void main(String args[]) throws Exception {
    myMeth();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Annotation Default Values
  2. Syntax for Java Annotation Default Values
  3. Example - How to use the default value from an annotation
Home »
  Java Tutorial »
    Java Langauge »
      Java Annotations
Java Annotations
Java Annotation retention policy
Java Annotation reflection
Java Annotation Default Values
Java Marker annotation
Java Single-Member Annotations
Java Built-In Annotations