Why Lombok @Data + @Builder Removes No‑Args Constructor and How to Fix It
This article explains why combining Lombok's @Data and @Builder annotations eliminates the default no‑argument constructor, demonstrates the compilation issues it causes, and provides two practical solutions—including using @Tolerate or separating constructors with @RequiredArgsConstructor and @NoArgsConstructor—while also detailing Lombok's compilation mechanism and a custom annotation example.
Problem Background
Lombok throws a compilation error when @Data and @Builder are used together because the generated no‑argument constructor disappears, which many frameworks rely on to instantiate objects.
Lombok @Data and @Builder Usage
@Data generates getters, setters, and a no‑argument constructor. @Builder generates an all‑args constructor but does not create getters/setters. When both are applied, the no‑argument constructor is omitted.
Solution Method 1
Manually add the @Tolerate annotation to the no‑argument constructor so Lombok ignores it during generation.
Solution Method 2
Separate constructors: use @RequiredArgsConstructor for the all‑args constructor and @NoArgsConstructor for the no‑argument constructor.
Lombok Principle
Java compilation consists of parsing, annotation processing, analysis, bytecode generation, and class file creation. Lombok uses JSR‑269 (Pluggable Annotation Processing API) to modify the abstract syntax tree (AST) during compilation, injecting code before the final bytecode is produced.
Lombok operates as an annotation processor that transforms Lombok annotations into regular Java code.
During the compilation phase, Lombok modifies the AST to add new nodes, then the compiler generates the final .class file.
Custom Annotation Example
The article demonstrates creating a simple @MySetter annotation and a corresponding annotation processor to generate setter methods at compile time.
After implementing the processor and compiling it, the test class shows the generated setter method in the resulting .class file.
Summary
While Lombok can generate setters and constructors automatically, the generated code exists only after compilation, so developers cannot invoke the methods directly in source. Lombok’s plugin mechanism bridges this gap, allowing seamless use of generated features during development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
