How to use Java annotation leasing strategy of class

I'm using comments to generate documents for the API I'm publishing I define 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 when I use reflection processing classes I can get a list of comments for this method My problem is that it works only when I instantiate a new instance of the object I'm working on I'd rather not instantiate them to get comments I tried retentionpolicy Class, but it doesn't work

Any ideas?

Solution

You don't need to instantiate the object, just 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());
      }
    }
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>