Lombok builder override default constructor
Asked Answered
B

2

5

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
    }
}
Burnham answered 26/11, 2018 at 6:14 Comment(1)
haha yup i did upvoted your answer :)Burnham
W
6

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.

Wormseed answered 26/11, 2018 at 7:53 Comment(0)
B
4

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.

Braziel answered 26/11, 2018 at 11:3 Comment(3)
Lombok 1.18.2 added @SuperBuilder, which is in most inheritance cases superior to the workaround you linked to.Wormseed
@JanRieke That's right but it's not supported yet in IDEA...Braziel
Yep, it's a pity :(Wormseed

© 2022 - 2024 — McMap. All rights reserved.