Video in progress
How does an annotation processor (Lombok, MapStruct) differ from runtime reflection?
An annotation processor runs inside javac at build time and writes new source code, so there's no cost at runtime. Reflection reads the annotation while the application is running: it's flexible, but slower, and errors show up later.
📖 Answer
Compile-time (JSR 269):
@Mapper(componentModel = "spring")
interface UserMapper {
UserDto toDto(User u);
}
// MapStruct generates UserMapperImpl.java at build time:
// plain getter/setter calls, no reflection
- errors (for example, a mismatched field) show up at build;
- you can open the generated code in
target/generated-sourcesand debug it; - it works with GraalVM native image without problems.
Runtime reflection (Spring DI, Jackson, Hibernate):
- behavior changes depending on the configuration and the classpath;
- slow on the first call, then faster with caching and bytecode generation;
- an error shows up only when the application starts or on a specific request.
Lombok is a special case. It goes outside the official API: it doesn't create a new file, it modifies javac's internal AST. That's why when a new JDK comes out, the Lombok version has to be updated too.
What you often see in practice:
- if Lombok and MapStruct are used together, the order in
annotationProcessorPathsmatters, and you needlombok-mapstruct-binding; - if "Enable annotation processing" is off in the IDE, the code is red in the IDE but green in Maven.
Sign up to mark studied questions and save your progress.