我有一个类,我想使用Lombok.Builder,我需要预处理一些参数.像这样的东西:
@Builder public class Foo { public String val1; public int val2; public List<String> listValues; public void init(){ // do some checks with the values. } }
通常我会在NoArg构造函数上调用init(),但是使用生成的构建器我无法这样做.有没有办法让生成的构建器调用此init?例如,build()将生成如下代码:
public Foo build() { Foo foo = Foo(params....) foo.init(); return foo; }
解决方法
经过多次试验和结束错误后,我找到了一个合适的解决方案:扩展生成构建器并自己调用init().
例:
@Builder(toBuilder = true,builderClassName = "FooInternalBuilder",builderMethodName = "internalBuilder") public class Foo { public String val1; public int val2; @Singular public List<String> 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; } } }