Video in progress

What problems come up when moving a reflection-heavy application to a GraalVM native image, and how does that affect the architecture?

Native image works on a "closed world" assumption: reflection, dynamic proxies, resources and class loading that aren't visible at build time don't work at runtime. You have to declare them with metadata or move to AOT code generation. In return, startup is in milliseconds and memory use is low.

📖 Answer

On the JVM everything is dynamic: Class.forName(nameFromConfig) works, because the class is loaded at runtime. Native image, on the other hand, statically analyzes at build time which code is reachable and throws the rest away.

What breaks:

  • Class.forName, getDeclaredMethods, newInstance: if the class isn't in the metadata, you get ClassNotFoundException or an empty result;
  • java.lang.reflect.Proxy: the list of interfaces has to be known ahead of time;
  • getResource: null if the resources weren't included in the image;
  • runtime bytecode generation (old CGLIB, some ORMs): doesn't work at all;
  • static initializers may run at build time, so a socket opened there or a System.currentTimeMillis() read there gets "frozen" into the image.

What you can do:

  1. reflect-config.json and other metadata (META-INF/native-image/...). Writing them by hand is hard; the tracing agent (-agentlib:native-image-agent) collects them during tests, but only for the paths the tests cover.
  2. Spring Boot 3 AOT: it turns bean definitions into Java code at build time, and you declare additional reflection through the RuntimeHints API.
  3. The GraalVM Reachability Metadata repository for libraries.

The effect on architecture is the heart of this staff-level question:

  • you give up the "read a class name from config and create it with reflection" style, and use ServiceLoader or an explicit registry instead;
  • runtime conditions like @Profile/@ConditionalOnProperty get frozen at build time; one image means one configuration;
  • build time stretches to minutes, and CI resource use goes up;
  • peak throughput is often lower than a JIT-based JVM (it gets closer with PGO).

When it's worth it: serverless, CLIs, small services that scale out quickly, memory-constrained environments. For a long-running, high-throughput service, JVM + CDS/AppCDS or CRaC is usually the cheaper solution. I make the decision with two numbers: startup and p99 latency, and RSS memory, measured in both variants.