V6081. Annotation that does not have 'RUNTIME' retention policy will not be accessible through Reflection API.

This diagnostic rule detects failed attempts to use the Reflection API for detecting annotations that do not have the 'RUNTIME' retention policy.

When an annotation is implemented, the 'Retention' meta-annotation needs to be applied to it to specify the annotation's lifetime:

  • RetentionPolicy.SOURCE – annotations will be present only in source code.
  • RetentionPolicy.CLASS – annotations will also be present in compiled code.
  • RetentionPolicy.RUNTIME – annotations will also be visible at runtime.

If you have not meta-annotated your annotation with 'Retention', it will be defaulted to 'CLASS'.

When using the Reflection API to get information about any annotations present, you should keep in mind that only annotations with the 'RUNTIME' retention policy will be visible to reflection. An attempt to get information about an annotation that has the 'SOURCE' or 'CLASS' retention policy will fail.

Consider the following contrived example. Suppose we have the following annotation in our project:

package my.package;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ....})
public @interface MyAnnotation {
  int field_id() default -1;
  String field_name() default "";
  ....
}

Trying to check if a certain method has that annotation using the Reflection API:

void runMethod(Method method, ....)
{
  ....
  if (method.isAnnotationPresent(MyAnnotation.class))
  {
    ....
  }
  ....
}

will result in getting false all the time. This happens because the annotation was not marked with the 'Retention' meta-annotation. And, as said earlier, if it is not specified, the default value is 'CLASS'.

For your annotation to be accessible through the Reflection API, you need to explicitly specify the 'RUNTIME' retention policy:

package my.package;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ....})
public @interface MyAnnotation {
  int field_id() default -1;
  String field_name() default "";
  ....
}

In addition to the 'isAnnotationPresent' method, this diagnostic rule also checks getAnnotation, getAnnotationsByType, getDeclaredAnnotation, and getDeclaredAnnotationsByType.


Bugs Found

Checked Projects
412
Collected Errors
14 132
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept