Thursday, April 28, 2011

Obtaining annotations at runtime using reflection

You can use getAnnotation method on Class of object, which has annotation attached to it.

Defining an annotation

package com.vaani.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnno {
String value();
String greetTo();
}

 

Using the annotations


Note that I have kept value as German words, corresponding to greetTo which is in english lanaguage.

@HelloAnno(value = "Gooten Morgen", greetTo = "GoodMorning")
public class AnnotationUser{
@HelloAnno(value = "Gooten Tag", greetTo = "Hi")
public void sayHi() {
}
//
@HelloAnno(value = "Gute Nacht", greetTo = "GoodNight")
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();
}
}
}


 


Method to print all annotation




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

//Prints Annotation Type: interface com.vaani.annotations


}

HelloAnno anno = (HelloAnno) clazz.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());
//Outputs
Anno value : Gooten Morgen
Anno GreetTo : GoodMorning


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());

 

//Outputs
Anno value : Gooten Tag
Anno GreetTo : Hi



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





Runner or tester class to show annotation:


public static void main(String[] args) {
GettingAnnotation demo = new GettingAnnotation();
Class clazz = demo.getClass();
printAnnotation(clazz);
}

No comments:

Post a Comment

Chitika