How to run code after constructor in a Lombok builder

后端 未结 4 1648
庸人自扰
庸人自扰 2021-02-07 01:38

I have a class that I want to use Lombok.Builder and I need pre-process of some parameters. Something like this:

@Builder
public class Foo {
   public String val         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 02:20

    After much trial and end error I found a suitable solution: extend the generate builder and call init() myself.

    Example:

    @Builder(toBuilder = true, builderClassName = "FooInternalBuilder", builderMethodName = "internalBuilder")
    public class Foo {
    
       public String val1;
       public int val2;
       @Singular public List listValues;
    
       void init() {
          // perform values initialisation
       }
    
       public static Builder builder() {
          return new Builder();
       }
    
       public static class Builder extends FooInternalBuilder {
    
          Builder() {
             super();
          }
    
          @Override public Foo build() {
             Foo foo = super.build();
             foo.init();
             return foo;
          }
       }
    }
    

提交回复
热议问题