mercredi 29 septembre 2021

Lombok @Builder for a class in multiple level of inheritance with mandatory fields

I'd like to implement Builder pattern for a class in deeper level of inheritance where some fields are mandatory (message, cause) and some optional (myOptField1, myOptField2...) by using Lombok @Builder and assuming that the parent class cannot be changed. So I've implemented my own builder() like this:

@Builder(toBuilder = true)
@Getter
public class MyException extends Exception {

    private int    myOptField1;
    private String myOptField2;

    public static MyExceptionBuilder builder(String message, Throwable cause) {
        return new MyException(message, cause).toBuilder();
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }
}

Then using of this class can be this way:

MyException
    .builder("Mandatory message", new SpecificException("specificCause"))
    .myOptField2("value")
    .build();

In IntelliJ Idea, everything seems to be fine but I get compilation error:

java: constructor MyException in class com.myproject.MyException cannot be applied to given types;
required: java.lang.String,java.lang.Throwable
found: int,java.lang.String
reason: actual and formal argument lists differ in length

So compiler can see only constructor generated by Lombok @Builder (=@AllArgsConstructor) and cannot see my constructor with parameters java.lang.String,java.lang.Throwable. Is there any better way how to solve this?

Aucun commentaire:

Enregistrer un commentaire