简体   繁体   English

龙目岛@Builder class 和 generics

[英]Lombok @Builder on class with generics

Is there a way to use Lombok's @Builder with Java generics?有没有办法将 Lombok 的@Builder与 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:稍后在处理来自 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:无法调用page方法:

The method page(List<Object>) in the type Response.ResponseBuilder<Object> is not applicable for the arguments ( List<Article> ) Response.ResponseBuilder<Object>类型中的方法page(List<Object>)不适用于 arguments ( List<Article> )

Any ideas?有任何想法吗?

You'll need to specify a "type witness", the 2nd <Article> part below:您需要指定一个“类型见证”,即下面的第二个<Article>部分:

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.这真的和Lombok无关,而是Java的类型推断的一个缺点。 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.它无法通过方法调用链推断builder()需要创建 Article 类型的 Response,即使它最终被分配给该类型的变量。

The type witness is a way of overriding the inference and specifying the generic type parameter explicitly.类型见证是一种覆盖推理并显式指定泛型类型参数的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM