java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to get all annotations?

To obtains all annotations for classes, methods, constructors, fields or packages we use the getAnnotations()method. This method returns an array of Annotation.

In the following example we tried to read all annotations from the sayHi method. First we need to obtain the method it self. Because the sayHi has parameters we need to pass not only the method name to the getMethod() method, we also need to pass the parameters type of the method.

The getAnnotations() method will return only annotation that has a RetentionPolicy.RUNTIME. Because other retention policy doesn't allow the annotation to available at runtime.

package com.javacoderanch.example.annotation;

import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Method;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.CLASS)
@interface MyAnno {
    String value();
}

public class GetAllAnnotation {
    public static void main(String args[]) {
        GetAllAnnotation demo = new GetAllAnnotation();
        demo.sayHi("001", "Alice");
        demo.sayHi("004", "Malory");

        try {
            Class clazz = demo.getClass();

            //
            // To get the sayHi method we need to pass not only the method name
            // but also its parameters type so the the getMethod() method return
            // the correct method for us to use.
            //
            Method method = clazz.getMethod("sayHi", String.class, String.class);

            //
            // Get all annotations from the sayHi method. But this will only
            // return 1 annotation actually. Because only the HelloAnno
            // annotation that has RUNTIME retention policy, which means that
            // the other annotations associated with sayHi method is not
            // available at runtime.
            //
            Annotation[] annotations = method.getAnnotations();
            for (Annotation anno : annotations) {
                System.out.println(anno.annotationType());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    @MyAnno("Hi")
    @HelloAnno(value = "Hello", greetTo = "Everyone")
    public void sayHi(String dataId, String name) {
        Map data = getData();
        if (data.containsKey(dataId)) {
            System.out.println("Hello " + data.get(dataId));
        } else {
            data.put(dataId, name);
        }
    }

    public Map<String, String> getData() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("001", "Alice");
        data.put("003", "Bob");
        data.put("003", "Carol");

        return data;
    }
}