如何在Lombok构建器中的构造函数之后运行代码 [英] How to run code after constructor in a Lombok builder
问题描述
我有一个类,我想使用Lombok.Builder,我需要预处理一些参数。这样的事情:
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 val1;
public int val2;
public List<String> listValues;
public void init(){
// do some checks with the values.
}
}
通常我会打电话给在NoArg构造函数上的init()
,但是使用生成的构建器,我无法这样做。有没有办法让生成的构建器调用 init
?例如 build()
将生成如下代码:
normally I would just call init()
on a NoArg constructor, but with the generated builder I'm unable to do so. Is there a way for this init
be called by the generated builder? For example build()
would generate a code like:
public Foo build() {
Foo foo = Foo(params....)
foo.init();
return foo;
}
我知道我可以手动编码所有args
构造函数,Builder将通过它调用,我可以在那里调用 init
。
I'm aware that I can manually code the all args
constructor, that the Builder will call through it and I can call init
inside there.
但这是一个次优解决方案,因为我的类可能会偶尔添加新字段,这也意味着更改构造函数。
But that is a sub-optimal solution as my class will likely have new fields added every once in a while which would mean changing the constructor too.
推荐答案
在 Foo
中你可以手动添加一个构造函数,让它进行初始化,然后放入 @Builder
在构造函数上。我知道您已经知道这一点,但我认为这是正确的解决方案,您不会忘记添加参数,因为您确实想要使用构建器中的代码。
In Foo
you could manually add a constructor, have that do the initialization, and put @Builder
on the constructor. I know that you already know this, but I think it is the right solution, and you won't forget to add the parameter since you do want to use the code in the builder anyway.
披露:我是一名lombok开发者。
Disclosure: I am a lombok developer.
这篇关于如何在Lombok构建器中的构造函数之后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!