简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM