Video in progress
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. UseAopUtils.getTargetClass()orAnnotationUtils.findAnnotation(). - Inheritance. Method annotations aren't inherited when the method is overridden.
@Inheritedworks only at class level and only from a superclass, not from an interface. - Meta-annotation. If
@Auditedsits inside another annotation, a plaingetAnnotationdoesn't see it: you need Spring'sMergedAnnotations. - 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.
Sign up to mark studied questions and save your progress.