views:

57

answers:

3

Hi all,

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?

+2  A: 

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:

  • An instance of that class is created
  • An instance of one of its subclasses is initialized
  • One of its static fields is initialized

So, in your case, merely referencing its name for reflection purposes is not enough to trigger its loading, and you cannot see the annotations.

Olivier Croisier
+3  A: 

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());
      }
    }
  }
}
True Soft
+2  A: 

You can get the annotations for a class using bean introspection:

Class<?> mappedClass;
BeanInfo info = Introspector.getBeanInfo(mappedClass);
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();

for (PropertyDescriptor descriptor : descriptors) {
    Method readMethod = descriptor.getReadMethod();
    PropertyInfo annotation = readMethod.getAnnotation(PropertyInfo.class);
    if (annotation != null) {
        System.out.println(annotation.description());
    }

}
Péter Török