Video in progress

Strong Middle ☕ Core Java

An annotation I wrote isn't visible through reflection at runtime. What could be the reason?

Most often @Retention(RUNTIME) was forgotten: the default is CLASS, so the annotation is in the bytecode but reflection doesn't see it. Or the lookup is going through a proxy class or a bridge method.

📖 Answer

There are three retention levels:

Retention Where it lives Who uses it
SOURCE only in the source code the compiler, annotation processors (@Override, Lombok)
CLASS (default) in the .class file, not loaded by the JVM bytecode tools
RUNTIME at runtime, via reflection Spring, Hibernate, Jackson
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Audited {
    String value() default "";
}

Even with the right retention, it may not be found:

  • Proxy. A Spring CGLIB proxy is a subclass. bean.getClass().getMethod(...) returns the proxy's method, which doesn't have the annotation. Use AopUtils.getTargetClass() or AnnotationUtils.findAnnotation().
  • Inheritance. Method annotations aren't inherited when the method is overridden. @Inherited works only at class level and only from a superclass, not from an interface.
  • Meta-annotation. If @Audited sits inside another annotation, a plain getAnnotation doesn't see it: you need Spring's MergedAnnotations.
  • Bridge method. A bridge in getDeclaredMethods() may not carry the annotation.

Put @Target on it too: if the annotation lands in the wrong place, the compiler tells you right away.