我想用fluent Api来减少一个方法的参数列表。我不想为此创建构造函数,所以我用 Lombok-@Builder 注释该方法:
@Builder
public static void test(User user, Item item, int age, Map<String, Test> tests, LocalDateTime time, String desc){
..method related things..
}
现在,我希望使用@Builder 的 Fluent-Api 调用该方法:
test.withUser(u).withItem(i)...build();
但是,由于我在该方法周围没有任何 getter 和 setter,因此该方法不存在流畅的 Api。这是在方法上正确使用 @Builder 吗?
最佳答案
这就是您使用默认 Builder 语法的方式。
@Builder
public static void test(User user, Item item){
// ...
}
public void buildTestExample(){
builder()
.user(new User())
.item(new Item())
.build();
}
但是,您可以像这样指定方法名称:
@Builder(builderMethodName = "buildTest")
public static void test(User bar, Item item){
// ...
}
public void buildTestExample(){
buildTest()
.user(new User())
.item(new Item())
.build();
}
参见 https://projectlombok.org/features/Builder
A method annotated with @Builder (from now on called the target) causes the following 7 things to be generated:
- An inner static class named FooBuilder, with the same type arguments as the static method (called the builder).
- In the builder: One private non-static non-final field for each parameter of the target.
- In the builder: A package private no-args empty constructor.
- In the builder: A 'setter'-like method for each parameter of the target: It has the same type as that parameter and the same name. It returns the builder itself, so that the setter calls can be chained, as in the above example.
- In the builder: A build() method which calls the method, passing in each field. It returns the same type that the target returns.
- In the builder: A sensible toString() implementation.
- In the class containing the target: A builder() method, which creates a new instance of the builder.
这是一个任意示例,表明您可以为 2 个方法使用 2 个构建器,并且它工作正常。
@Builder(builderMethodName = "buildFoo")
public static String foo(String param1, String param2){
return "foo" + param1 + param2;
}
@Builder(builderMethodName = "buildBar")
public static String bar(String param1, String param2){
return "bar" + param1 + param2;
}
@Test
public void test(){
assertThat(buildFoo().param1("h").param2("w").build()).isEqualTo("foohw");
assertThat(buildBar().param1("h").param2("w").build()).isEqualTo("foohw");
}
关于java - lombok @Builder 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083756/