How to use Java annotation policy for CLASS

I use annotations to create documentation for the API that I am posting. I defined it as follows:

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyInfo {

    String description();

    String since() default "5.8";

    String link() default "";
}

Now this works great when I process classes using reflection. I can get a list of annotations by method. The problem is that it only works if I instantiate a new instance of the object that I am processing. I would prefer not to instantiate in order to get annotation. I tried RetentionPolicy.CLASS, but it does not work.

Any ideas?

+3
source share
3 answers

You do not need to instantiate the object, you just need a 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());
      }
    }
  }
}
+3
source

Java5, .

, , . , :

, , , .

+2

You can get annotations for the 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());
    }

}
+2
source

Source: https://habr.com/ru/post/1748542/


All Articles