Java / MapStruct Java Interview questions part 2
What is the difference between MapStruct's compile-time approach and CGLIB proxy-based mapping?
CGLIB-style approaches generate subclasses or proxies at runtime (via bytecode generation libraries) to intercept method calls and perform mapping or enhancement dynamically as the application runs.
| MapStruct | CGLIB-style proxying |
| Mapping class generated once, at compile time. | Proxy/subclass generated at runtime, usually on first use. |
| No extra classloading cost during startup. | Adds bytecode generation and classloading overhead at startup or first call. |
Generated code is visible, ordinary .java/.class files. | Proxy bytecode is generated dynamically, harder to inspect or debug. |
| Errors caught by the compiler. | Errors typically only surface when the proxy method is actually invoked. |
The trade-off is flexibility versus predictability: runtime proxying can adapt to types it has never seen before without recompilation, while MapStruct requires a build step but gives you certainty about what a mapping will do before the application ever starts.
More Related questions...