How to implements Lombok @Builder for Abstract class

sam picture sam · Jul 6, 2018 · Viewed 13k times · Source

I have classes that extend an abstract class and I don't want to put @Builder on top of the all child classes.

Is there any way to implement Lombok @Builder for an abstract class?

Answer

Jan Rieke picture Jan Rieke · Jul 9, 2018

This is possible with lombok 1.18.2 (and above) using the new (experimental) annotation @SuperBuilder. The only restriction is that every class in the hierarchy must have the @SuperBuilder annotation. There is no way around putting @SuperBuilder on all subclasses, because Lombok cannot know all subclasses at compile time. See the lombok documentation for details.

Example:

@SuperBuilder
public abstract class Superclass {
    private int field1;
}

@SuperBuilder
public class Subclass extends Superclass {
    private int field2;
}

Subclass instance = Subclass.builder().field1(1).field2(2).build();