I'm using Lombok's @Builder
annotation and need to add a custom setter method, as well as enhancing the build() method.
However, I'm stuck with two solutions where none covers both requirements at once and one contradicts the other.
They vary between the direct Builder override and an inherited Builder.
The code contains those two variants and describes what is and what isn't working.
public class LombokCustomBuilderWithCustomSetterAndBuildMethodExamples {
/**
* Without builder inheritance
*/
@Builder
public static class ExampleA {
private String someField;
/**
* Directly overwrites the Lombok builder
*/
private static class ExampleABuilder {
/**
* this works
*/
public ExampleABuilder someCustomSetter(String someValue) {
this.someField = someValue.toUpperCase();
return this;
}
/**
* super.builder() not available, as we have overwritten the Lombok's build() method entirely.
* We would need to re-implement the functionality by ourselves
*/
public ExampleA build() {
ExampleA myCreatedObject = super.build();
if (myCreatedObject.someField == null) throw new RuntimeException("Some validation failed");
return myCreatedObject;
}
}
}
/**
* With child and parent builder inheritance
*/
@Builder
public static class ExampleB {
private String someField;
private static class CustomExampleBBuilder extends ExampleBBuilder {
/**
* this does not work, as this.someField now has private access
*/
public CustomExampleBBuilder someCustomSetter(String someValue) {
this.someField = someValue.toUpperCase();
return this;
}
/**
* This works, super.build() is available, we are using the Lombok's build() result
* and won't have to rewrite it
*/
@Override
public ExampleB build() {
ExampleB myCreatedObject = super.build();
if (myCreatedObject.someField == null) throw new RuntimeException("Some validation failed");
return myCreatedObject;
}
}
}
}
On one hand, I'd need the inheritance so the build()
method does not need to be reimplemented, on the other hand I cannot access the field of the class I need to set with the custom setter method.
How can I reuse the existing build()
method's result after the object has been built and at the same time have my custom setter method?