Niccolò
Niccolò

Reputation: 3092

How can Lombok's @Builder/@AllArgsConstructor invoke a custom constructor?

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?

Upvotes: 1

Views: 2530

Answers (1)

maaartinus
maaartinus

Reputation: 46382

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.

Upvotes: 2

Related Questions