Lombok @Builder in Parent Child Relationship / Inheritance

Lombok has a decent set of annotations that can help developers avoid writing boiler plate code. Among the Lombok’s universal set, Builder and AllArgsConstructor are popular in assisting programmers to generate means to create object instances. If interested, check the performance comparison between builder and all arguments constructor.

In one of the recent scenarios encountered, the application had a custom Exception which was created by extending RuntimeException and contained a few custom fields for defining application error scenarios. As auto generated constructors started getting bigger, it was preferable to go with builder pattern to generate instances. @Builder annotation, by design will generate builder considering only the fields of the same class and not the parent class. This has been an open request for years and not addressed by the Lombok developers.

This has an easy workaround and straight forward to overcome even when parent class is not in your control. The solution is to add the @Builder annotation on the longest all arguments constructor which includes all the parent fields that are required, and not on the class definition.

Consider the two classes defined below:

 @Builder
 class MyException extends RuntimeException{
 private int customErrorCode;
 }
class OtherException extends RuntimeException{
 private int customErrorCode;

 @Builder
 public OtherException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, int customErrorCode) {
 super(message, cause, enableSuppression, writableStackTrace);
 this.customErrorCode = customErrorCode;
 }
 }

Auto generated builders for each would look like below:

Result of @Builder for class

Result of @Builder on constructor