Hi all,
I realized today that It is possible to create its own builder, derived from the one generated by Lombok, as a work-around to provide default values to the builder:
@Getter
@Builder(builderClassName = "LombokBuilder")
public class Point {
private final double x;
private final double y;
private final double z;
private String name;
public static MyPointBuilder builder() {
return new MyPointBuilder();
}
public static class MyPointBuilder extends LombokBuilder {
public MyPointBuilder() {
z(-99.9); // Provide a default value for the z attribute
}
}
}
This works pretty well !
An idea is to use this mechanism to check that mandatory attributes are initialized by overriding the
build() method. In my example, this would be done by adding this to
MyPointBuilder:
public static class MyPointBuilder extends LombokBuilder {
...
@Override
public Point build() {
if (name == null) throw new IllegalArgumentException("name attribute is mandatory");
return super.build();
}
...
}
However, this not currently possible since builder attributes are private :-( Maybe it would be a good idea to make them protected in a future version ?
Any opinion on this way of proceeding ?
Philippe