Annotations and reflection: Retention

The other day I tried to perform the following code:

public @interface MyAnn {
String value();
}

@MyAnn(value = "foo")
public class MyClass {
}
..
MyClass.class.getAnnotation(MyAnn.class).value();

This gave me a NullPointerException because the annotation was not found.
I cursed, I googled, and I felt stupid for a whole day ;)

Later, I figured out it has something to do with retention. It’s an annotation which tells the VM how long the annotation has to be retained.

So the solution to my problem was just setting the right retention policy on my annotation:

@Retention(Retention.RUNTIME)
public @interface MyAnn {
String value();
}

For more info refer to the javadoc: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/Retention.html
Source: http://java.nullpointer.be/2009/12/annotations-using-reflection.html

Comments are closed.