Reputation: 5708
I want to use fluent Api to reduce the parameter list of a method. I dont want to create a constructor for this, so I annote the method with Lombok-@Builder:
@Builder
public static void test(User user, Item item, int age, Map<String, Test> tests, LocalDateTime time, String desc){
..method related things..
}
Now, I expect to call that method with the Fluent-Api of @Builder:
test.withUser(u).withItem(i)...build();
However, as I do not have any getters and setters around the method, no fluent Api exists for that method. Is this the right use of @Builder on a method?
Upvotes: 1
Views: 5841
Reputation: 4809
This is how you use the default Builder syntax.
@Builder
public static void test(User user, Item item){
// ...
}
public void buildTestExample(){
builder()
.user(new User())
.item(new Item())
.build();
}
However, you can specify the method name like so:
@Builder(builderMethodName = "buildTest")
public static void test(User bar, Item item){
// ...
}
public void buildTestExample(){
buildTest()
.user(new User())
.item(new Item())
.build();
}
See 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.
Here is an arbitrary example showing that you can have 2 Builders for 2 methods and it works fine.
@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");
}
Upvotes: 6