getAnnotations() Method - Annotation APIs

This section provides a tutorial example on how to use the getAnnotations() method and other annotation APIs to obtain annotation information at runtime.

In previous tutorials, we have learned how to declare your own annotation types and use them in annotation invocation statements.

Your own annotation types can help you adding information to your Java source code in a more structured way. But need to build your own tools to parse, validate and process annotated information.

Building an annotation process tool can be done by writing a standalone program in any programming language. But you can also use Java reflection facility obtain annotated information at runtime for processing

Here are some Java APIs that you can use to obtain annotated information at runtime.

1. java.lang.annotation package - Contains interfaces and classes to support annotation APIs.

2. @Retention(value=RetentionPolicy.RUNTIME) annotation - Annotates your annotation declarations so that they are retained in a runtime virtual machine.

3. Class.getAnnotations() method - Returns all annotations associated with this class.

4. Method.getAnnotations() method - Returns all annotations associated with this method.

5. Field.getAnnotations() method - Returns all annotations associated with this field (static or instance variable).

Here is a sample program that shows you how to use Java annotation APIs to obtain annotated information at runtime for processing

/* GetAnnotationsTest.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.lang.annotation.*;
class GetAnnotationsTest {

   @Retention(value=RetentionPolicy.RUNTIME)
   @interface Herong {
      String value() default "Herong";
      String email() default "herong@nowhere.com";
   }

   @Retention(value=RetentionPolicy.RUNTIME)
   @interface John {
      String value() default "John";
      String email() default "john@nowhere.com";
   }

   @John public static String msg = "Hello world!";

   @Herong public static void main(String[] arg) {
      java.io.PrintStream out = System.out;

      try {
        // processing annotations on a class
        java.lang.Class cls = Dummy.class;
        Annotation[] list = cls.getAnnotations();
        out.println("Annotations on class: "+cls.getName());
        for (Annotation a: list) {
           out.println("   "+a);
        }

        // processing annotations on a method
        java.lang.reflect.Method mtd =
           GetAnnotationsTest.class.getMethod("main", String[].class);
        list = mtd.getAnnotations();
        out.println("Annotations on method: "+mtd.getName());
        for (Annotation a: list) {
           out.println("   "+a);
        }

        // processing annotations on a field (variable)
        java.lang.reflect.Field fld =
           GetAnnotationsTest.class.getField("msg");
        list = fld.getAnnotations();
        out.println("Annotations on field: "+fld.getName());
        for (Annotation a: list) {
           out.println("   "+a);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }

      // normal execution
      out.println(msg);
   }

   @Herong @John public class Dummy {}
}

If you compile and run the program, you will get:

herong> java GetAnnotationsTest.java

Annotations on class: GetAnnotationsTest$Dummy
   @GetAnnotationsTest$Herong(value="Herong", email="herong@nowhere.com")
   @GetAnnotationsTest$John(value="John", email="john@nowhere.com")
Annotations on method: main
   @GetAnnotationsTest$Herong(value="Herong", email="herong@nowhere.com")
Annotations on field: msg
   @GetAnnotationsTest$John(value="John", email="john@nowhere.com")

Hello world!

As you can see, I can easily obtain annotated information and generate a nice report now.

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 Enum Types and Enum Constants

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Assert Statements and -ea" Option

Annotation Statements and Declarations

 What Is Annotation

 Use "interface" as Annotation

 Default Values for Annotation Elements

 Single-Element Annotation Invocation

 No-Element (Marker) Annotation Invocation

getAnnotations() Method - Annotation APIs

 Predefined Annotation Types

 Java Related Terminologies

 Archived Tutorials

 References

 Full Version in PDF/EPUB