SteelReed

Search

Search posts, questions…

3. Advanced Java

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.

19 Nov 20267 min readSenior

–

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

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 javac plugin: it reads annotations, validates, generates new files through Filer, and reports errors on the right line via Messager (don't throw exceptions). Generated files compile in the next round; output goes to target/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's annotationProcessorPaths, 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 javac internals, so it often breaks on JDK upgrades and needs a newer Lombok.
  • --add-opens java.base/java.lang=ALL-UNNAMED is 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; Method and Field are looked up once and cached.
  • No setAccessible into 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
  • @Inherited only works for superclasses, not interfaces: PaymentServiceImpl.class.isAnnotationPresent(Audit.class) returns false.
  • Fix: put @Audit on the implementation class (or on methods), or have the aspect look it up with AnnotatedElementUtils.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 isAnnotationPresent on 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, javac no longer runs processors it finds on the classpath. MapStruct doesn't generate OrderMapperImpl and Lombok doesn't generate getters.
  • 15 minutes: add -proc:full to 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-binding if you use both) in annotationProcessorPaths with 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.
  • setAccessible can't reach inside the JDK since JDK 17.
  • Annotations are just data; reflection only sees RUNTIME, and the default is CLASS.
  • @Inherited only follows superclasses; proxies don't wrap this calls.
  • 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

All Java Core questions →All Spring Boot questions →

Loading comments…
Next on the roadmapDatabases: choosing data types, primary keys, NULL and schema changes before the table gets big