How do I obtaion annotations at runtime using reflection?
Category: java.lang.annotation, viewed: 2646 time(s).
This example demonstrate how to obtaion 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.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@HelloAnno(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());
}
HelloAnno anno = (HelloAnno) clazz.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());
try {
Method m = clazz.getMethod("sayHi");
anno = m.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
demo.sayHello();
}
@HelloAnno(value = "Hi", greetTo = "Alice")
public void sayHi() {
}
@HelloAnno(value = "Hello", greetTo = "Bob")
public void sayHello() {
try {
Method m = getClass().getMethod("sayHello");
HelloAnno anno = m.getAnnotation(HelloAnno.class);
System.out.println(anno.value() + " " + anno.greetTo());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
You can find the HelloAnno 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.annotation.HelloAnno
Anno Value : Hello
Anno GreetTo: Universe
Anno Value : Hi
Anno GreetTo: Alice
Hello Bob
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!