1

I have a custom no-args constructor and I'd like the Builder generated by Lombok to invoke it. I think this is equivalent to have a constructor with all arguments invoking such a custom no-args constructor as first thing.

I'll explain with an example

@Builder
@Data
public class BuilderExample extends Foo{

  private String name;
  private int age;

  public BuilderExample(){
    super.setSome(thing);
  }

}

An instance created by BuilderExample.build() should set super.setSome(thing);

The only way I could find so far to achieve this, would be to write the all-args-constructor and make it invoke the no-args-one. I think this defeats all the idea of using Lombok's constructors and builders as if the number of fields is higher than one or two, the all-args-constructor becomes tedious to write and maintain.

Is there another way to achieve this?

1 Answer 1

2

You can define a nearly empty nested

class BuilderExampleBuilder {
    public BuilderExample build() {
        BuilderExample result = new ...all the stuff Lombok does
        result.setSome(thing);
        return result;
    }
}

but this has some problems:

  • The all-args-constructor is verbose and prone to forgetting a new field.
  • The call result.setSome(thing) can't use the super keyword. This is solvable by providing a method like

    private superSetSome(Thing thing) { super.setSome(thing); }

You can also use a non-static initializer block like

{
   super.setSome(thing);
}

That's all what can be done and there's no nice solution. There are no hooks allowing to inject code into the constructor nor the builder.

2
  • I admit I didn't know the non-static initializer blocks and that seems to be the solution to my problem (though somehow arcane)! I thought myself to provide a nearly empty builder class for Lombok, but I fear the build() method is not so simple nor clean to do so (see e.g. the example at the bottom of Lombok's doc projectlombok.org/features/Builder)
    – Niccolò
    Sep 27, 2018 at 15:15
  • @Niccolò Sure, non-static initializer blocks are rarely used as it's much cleaner and more flexible to do the initialization in the constructor or in the declaration. But there's no magic there, just note that they get executed before the constructor. +++ Sure, @Singular makes it more complicated, but if you use Guava (and pretty everybody should), then the "complicated switch statement to produce a compact properly sized immutable set omitted" shrinks to ImmutableSet.copyOf(MoreObjects.firstNonNull(this.occupations, ImmutableSet.of())). However, it's still tons of boilerplate.
    – maaartinus
    Sep 27, 2018 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.