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.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<? extends GettingAnnotation> clazz = demo.getClass();
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("Annotation Type: " + annotation.annotationType());
}
HelloAnnotation annotation = clazz.getAnnotation(HelloAnnotation.class);
System.out.println("Value : " + annotation.value());
System.out.println("GreetTo: " + annotation.greetTo());
try {
Method m = clazz.getMethod("sayHi");
annotation = m.getAnnotation(HelloAnnotation.class);
System.out.println("Value : " + annotation.value());
System.out.println("GreetTo: " + annotation.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 method = getClass().getMethod("sayHello");
HelloAnnotation annotation = method.getAnnotation(HelloAnnotation.class);
System.out.println(annotation.value() + " " + annotation.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.lang.annotation.HelloAnnotation
Value : Hello
GreetTo: Universe
Value : Hi
GreetTo: Alice
Hello Bob
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025