Is there a way to use Lombok's @Builder
with Java generics?
@Builder
public class Response<T> {
private String status;
private long total;
private List<T> page;
}
Later in a service that handles requests from controller:
long total = getTotalItemsCount();
List<Article> page = getPage();
Response<Article> response =
Response.builder()
.status("ok")
.total(total)
.page(page); // error on this line
It's not possible to call page
method:
The method
page(List<Object>)
in the typeResponse.ResponseBuilder<Object>
is not applicable for the arguments (List<Article>
)
Any ideas?
CodePudding user response:
You'll need to specify a "type witness", the 2nd <Article>
part below:
Response<Article> response =
Response.<Article>builder() // here
.status("ok")
.total(total)
.page(page)
.build();
This is really nothing to do with Lombok, but a shortcoming of Java's type inference. It cannot infer through the chain of method calls that builder()
needs to create a Response of type Article, even though it's ultimately assigned to a variable of that type.
The type witness is a way of overriding the inference and specifying the generic type parameter explicitly.