[英]Error with Lombok's @Builder with generic typed field
I am having issues creating a POJO using Lombok's @Builder
annotation and have it map to the expected type at runtime.我在使用 Lombok 的
@Builder
注释创建 POJO 并在运行时将其 map 设置为预期类型时遇到问题。
Here's my code:这是我的代码:
OperationResult.java操作结果.java
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class OperationResult<D>
{
private D data;
}
OperationResultTest.java操作结果Test.java
import org.junit.jupiter.api.Test;
public class OperationResultTest
{
@Test
public void testGenerics()
{
OperationResult<String> restult = OperationResult.builder()
.data("Test")
.build();
}
}
This results in a compilation error stating the returned type is OperationResult<Object>
and cannot be casted to the expected type of OperationResult<String>
.这会导致编译错误,指出返回的类型是
OperationResult<Object>
并且不能转换为OperationResult<String>
的预期类型。
Is it possible to use generics and know the returned type using Lombok's @Builder
annotation?是否可以使用 generics 并使用 Lombok 的
@Builder
注释知道返回的类型?
Thanks for your help!谢谢你的帮助!
To resolve the compilation error, you should define the generic when calling the builder()
method like so:要解决编译错误,您应该在调用
builder()
方法时定义泛型,如下所示:
OperationResult<String> result = OperationResult.<String>builder()
.data("Test")
.build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.