Reflection, annotations and annotation processors: how Java frameworks read your code
The reflection API and its cost, setAccessible's limits since JDK 17, dynamic proxies, @Retention and @Inherited, annotation processors that generate code at compile time, how Lombok differs from MapStruct, and choosing run time or compile time.
On this page
1. The problem
A team writes @Audit to log every sensitive method. An aspect reads it via reflection and tests pass on a sample class. In production not a single audit line appears: @Audit lacks @Retention(RUNTIME), so reflection returns null, and nothing reports an error.
2. Key idea
An annotation is a sticky note on code: by itself it does nothing. Reflection reads the note at runtime; an annotation processor reads it at compile time and prints an appendix (new files). @Target says where the note can go, @Retention how long it lives.
@Retention |
In the .class? |
Visible to reflection? | Used for |
|---|---|---|---|
SOURCE |
no | no | @Override, Lombok, processors |
CLASS (default) |
yes | no | bytecode tools |
RUNTIME |
yes | yes | @Service, @Entity, @Transactional |
Reflection goes from a Class to its Fields, Methods and Constructors and calls them without compile-time knowledge of the type. getMethods() returns public members including inherited ones; getDeclaredMethods() includes private but only for that class. Exceptions from invoked methods are wrapped in InvocationTargetException.
A dynamic proxy (Proxy, or CGLIB, Spring Boot's default) creates at runtime an object in front of the real one: the basis of @Transactional, caching, retries. this.other() bypasses the proxy, so annotations on internally called methods have no effect.
2.1 Reflection or code generation?
A direct call ~0.02 ns, a cached Method.invoke ~3.5 ns, MethodHandle.invokeExact ~1.5 ns (JDK 21, rough measurement). The expensive part is lookup (getMethod, scanning annotations), so frameworks do it once at startup.
| Approach | Use when | Don't use when |
|---|---|---|
| Runtime reflection (Spring, Jackson) | flexibility, dynamically loaded classes | hot paths in a service: use interfaces, switch, a key → lambda map |
| Compile-time generation (MapStruct, Micronaut) | errors at build time, fast startup, native images | reading classes unknown in advance |
3. In Java
@Retention(RetentionPolicy.RUNTIME) // without this line reflection returns null, silently
@Target(ElementType.METHOD) // anywhere else is a compile error
public @interface Audit { String level() default "INFO"; }
Method m = BookingService.class.getMethod("cancel", String.class);
Audit a = m.getAnnotation(Audit.class); // @Audit(level="WARN") or null
Field status = Booking.class.getDeclaredField("status");
status.setAccessible(true); // past private in your own class: fine
status.set(booking, "CANCELLED");
// String.class.getDeclaredField("value").setAccessible(true)
// -> InaccessibleObjectException since JDK 17 (strong encapsulation)@Inherited only follows the superclass, not interfaces, and never methods. Spring looks deeper than plain reflection (MergedAnnotations reads interfaces and meta-annotations), which is why @RestController acts as @Controller + @ResponseBody.
Annotation processors and Lombok
- A processor is a
javacplugin: it reads annotations, validates, generates new files throughFiler, and reports errors on the right line viaMessager(don't throw exceptions). Generated files compile in the next round; output goes totarget/generated-sources/annotations, never committed. - Since JDK 23, processors found on the classpath no longer run automatically (JDK 21 only warns). Declare them in
maven-compiler-plugin'sannotationProcessorPaths, or use--processor-path,-proc:full. Lombok, MapStruct, the Hibernate metamodel and the Spring Boot configuration processor all need this. - Lombok is different: it edits the syntax tree of the class being compiled (adding getters to it) through
javacinternals, so it often breaks on JDK upgrades and needs a newer Lombok. --add-opens java.base/java.lang=ALL-UNNAMEDis only a temporary escape hatch for old libraries reflecting into the JDK; the real fix is upgrading the library.
4. Working with AI
Delegate to AI: annotations and the aspects that read them, processors for repetitive code, annotationProcessorPaths configuration.
Check yourself:
- Annotations read via reflection have
@Retention(RUNTIME)and the right@Target. - Something actually reads the annotation (an aspect, a
BeanPostProcessor, a filter, a processor). - No reflection on hot paths;
MethodandFieldare looked up once and cached. - No
setAccessibleinto JDK classes; no long-term reliance on--add-opens. - Processors are declared explicitly in the build, not left on the classpath.
5. Exercises
Exercise 1: Review "@Audit applied to every service"
AI put @Audit on the PaymentService interface and declared it @Inherited, noting "every implementation is audited automatically". The annotation has @Retention(RUNTIME). The aspect uses @Around("@within(com.acme.Audit)"). No implementation gets audited. Why? Fix it and name a test.
Solution to Exercise 1
@Inheritedonly works for superclasses, not interfaces:PaymentServiceImpl.class.isAnnotationPresent(Audit.class)returnsfalse.- Fix: put
@Auditon the implementation class (or on methods), or have the aspect look it up withAnnotatedElementUtils.findMergedAnnotation(Spring reads interfaces too). - Test: call a method on the real bean through the context and assert an audit line; add a reflection test of
isAnnotationPresenton the impl class to catch it early. - Also remember: an internal
this.pay()call bypasses the proxy, so it isn't audited either.
Exercise 2: Read a JDK-upgrade incident
After moving from JDK 21 to JDK 25, the build fails with many cannot find symbol: class OrderMapperImpl and cannot find symbol: method getName() errors. The code hasn't changed. Diagnose, act within 15 minutes, fix the root cause.
Solution to Exercise 2
- Diagnosis: since JDK 23,
javacno longer runs processors it finds on the classpath. MapStruct doesn't generateOrderMapperImpland Lombok doesn't generate getters. - 15 minutes: add
-proc:fullto the compiler args to get builds running again, or pin CI back to JDK 21 temporarily. - Root fix: declare Lombok and MapStruct (plus
lombok-mapstruct-bindingif you use both) inannotationProcessorPathswith pinned versions; upgrade Lombok to a JDK 25-compatible release; build on the new JDK in CI before switching production.
Summary
- Reflection reads and calls code at runtime; look things up once and cache.
setAccessiblecan't reach inside the JDK since JDK 17.- Annotations are just data; reflection only sees
RUNTIME, and the default isCLASS. @Inheritedonly follows superclasses; proxies don't wrapthiscalls.- Processors generate new files at compile time; since JDK 23 they must be declared explicitly.
Further reading: IoC and dependency injection.
Self-compiled notes from official documentation and hands-on practice.
Practice interview questions on this topic
- What is reflection, what do frameworks use it for, and what are its downsides?
- What values does @Retention have? How does an annotation processor (like Lombok) differ from reflection?
- How would you lead the upgrade of a service from Java 8 to Java 21?
- How do JDK dynamic proxies and CGLIB proxies differ? Which does Spring Boot use by default?
Comments
Community rules