Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 942
sproketboy Avatar asked Dec 04 '25 17:12

sproketboy


2 Answers

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());
      }
    }
  }
}
like image 56
True Soft Avatar answered Dec 06 '25 08:12

True Soft


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.

like image 26
Olivier Croisier Avatar answered Dec 06 '25 08:12

Olivier Croisier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!