[英]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. 我有一个自定义的无参数构造函数,我想由Lombok生成的Builder调用它。 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);
由
BuilderExample.build()
创建的实例应设置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. 到目前为止,我能找到的唯一方法是编写all-args-constructor并使其调用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.
我认为这击败了使用Lombok的构造函数和构造函数的所有想法,就好像字段的数量大于一或两个,all-args构造函数的编写和维护变得乏味。
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 call result.setSome(thing)
can't use the super
keyword. 调用
result.setSome(thing)
不能使用super
关键字。 This is solvable by providing a method like 这可以通过提供类似的方法来解决
private superSetSome(Thing thing) { super.setSome(thing); 私人superSetSome(事物){super.setSome(事物); }
}
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.
没有钩子允许将代码注入到构造器或构造器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.