How do I obtain annotations at runtime using reflection?

This example demonstrate how to obtain annotations of a class and methods. We use the reflection API to get class and method information from where we can read information about annotation attached to the class or the method.

package org.kodejava.example.lang.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@HelloAnnotation(value = "Hello", greetTo = "Universe")
public class GettingAnnotation {
    public static void main(String[] args) {
        GettingAnnotation demo = new GettingAnnotation();

        Class clazz = demo.getClass();
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation anno : annotations) {
            System.out.println("Annotation Type: " + anno.annotationType());
        }

        HelloAnnotation anno = (HelloAnnotation) clazz.getAnnotation(HelloAnnotation.class);
        System.out.println("Anno Value  : " + anno.value());
        System.out.println("Anno GreetTo: " + anno.greetTo());

        try {
            Method m = clazz.getMethod("sayHi");

            anno = m.getAnnotation(HelloAnnotation.class);
            System.out.println("Anno Value  : " + anno.value());
            System.out.println("Anno GreetTo: " + anno.greetTo());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        demo.sayHello();
    }

    @HelloAnnotation(value = "Hi", greetTo = "Alice")
    public void sayHi() {
    }

    @HelloAnnotation(value = "Hello", greetTo = "Bob")
    public void sayHello() {
        try {
            Method m = getClass().getMethod("sayHello");
            HelloAnnotation anno = m.getAnnotation(HelloAnnotation.class);

            System.out.println(anno.value() + " " + anno.greetTo());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

You can find the HelloAnnotation annotation that we use above on the following example: How do I create a simple annotation?.

The result of our program is:

Annotation Type: interface org.kodejava.example.lang.annotation.HelloAnnotation
Anno Value  : Hello
Anno GreetTo: Universe
Anno Value  : Hi
Anno GreetTo: Alice
Hello Bob

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.