I just stumbled upon the same problem. But also, I wanted to add the buildOptional() method to the builder so as not to repeat Optional.of(Foo) every time I need it. This did not work previously because chained methods return FooInternalBuilder objects; and placing buildOptional() in FooInternalBuilder skip the execution of the init() method in Builder ...
In addition, I personally did not like the presence of two constructor classes.
Here is what I did instead:
@Builder(buildMethodName = "buildInternal") @ToString public class Foo { public String val1; public int val2; @Singular public List<String> listValues; public void init(){
You can perform a quick test using this basic method:
public static void main(String[] args) { Foo foo = Foo.builder().val1("String").val2(14) .listValue("1").listValue("2").build(); System.out.println(foo); Optional<Foo> fooOpt = Foo.builder().val1("String").val2(14) .listValue("1").listValue("2").buildOptional(); System.out.println(fooOpt); }
Let's do this to add what I want:
- Add an
init() method that starts automatically after each object construct. - Adding new fields does not require additional work (as it would be for an individually written constructor)
- Ability to add additional functions (including execution of
init() ) - Save the full standard functionality annotation
@Builder brings - Do not set an extra class class
Even if you solved your problem before I wanted to share it as a solution. This is a little shorter and adds (for me) a nice feature.
source share