Rahul Babu
Rahul Babu

Reputation: 790

Lombok builder override default constructor

I was setting the value of recordId from the child classes using the default constructor and was not using lombok @Builder initially. Eventually i decided to use the Builder here, but the problem now is lombok Builder overrides my default constructor internally hence the value is never set.

How can I put any hook too make lombok @Builder use my default constructor?

Parent class:

@Getter
@Setter
public abstract class Record {
    private String recordId;
}

Child class:

@Getter
@Setter
@Builder
@ToString
@AllArgsConstructor
public  class SRecord extends Record {
    private static final String RECORD_ID = "REC001";
    private String street;
    private String city;

    public SRecord() {
        setRecordId(RECORD_ID); //value of recordId being set
    }
}

Upvotes: 5

Views: 11812

Answers (2)

Cepr0
Cepr0

Reputation: 30309

I think you should create a constructor in your base class:

@Getter
@Setter
public abstract class Record {

    private String recordId;

    public Record(String recordId) {
        this.recordId = recordId;
    }
}

Then use it in the constructor of the inherited class:

@Getter
@Setter   
@Builder
public class SRecord extends Record {

    private static final String RECORD_ID = "REC001";

    private String street;
    private String city;  

    public SRecord(String street, String city) {
        super(RECORD_ID); 
        this.street = street;
        this.city = city;
    }
}

P.S. If you want to use Lombok Builder with inheritance you can use this technique.

Upvotes: 4

Jan Rieke
Jan Rieke

Reputation: 8042

Lombok's @Builder simply does not use the default constructor. It passes its values to an all-args constructor so that this constructor can fill the new instance with these values. @Builder does not use setters or direct access to the fields to do so. So your default constructor is simply ignored by @Builder.

What you can do is write your own all-args constructor. In it, you set your value for recordId and assign the rest of the fields from the parameters.

Upvotes: 6

Related Questions