I'm using annotations for generating documentation for an API that I'm publishing. I have it defined like this:
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyInfo {
String description();
String since() default "5.8";
String link() default "";
}
Now this works fine when I process the classes using reflection. I can get the list of annotations on the method. The issue I have is that it only works if I instantiate a new instance of the object I'm processing. I would prefer not to have to instantiate them to get the annotation. I tried RetentionPolicy.CLASS but it doesn't work.
Any ideas?
You don't need to instantiate an object, you just need the class. Here is an example:
public class Snippet {
@PropertyInfo(description = "test")
public void testMethod() {
}
public static void main(String[] args) {
for (Method m : Snippet.class.getMethods()) {
if (m.isAnnotationPresent(PropertyInfo.class)) {
System.out.println("The method "+m.getName()+
" has an annotation " + m.getAnnotation(PropertyInfo.class).description());
}
}
}
}
Starting from Java5, classes are loaded lazily.
There are somes rules that determine if a class should be loaded. The first active use of a class occurs when one of the following occurs:
So, in your case, merely referencing its name for reflection purposes is not enough to trigger its loading, and you cannot see the annotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With