简体   繁体   中英

How to use Java annotations rention policy for CLASS

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:

  • 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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM