[英]Lombok @SuperBuilder is not initializing my class objects
我有一个父类和一个子类,我使用@SuperBuilder
来构建子对象,但似乎它根本没有初始化。 我的父类看起来像这样:
@Getter
@Setter
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuperBuilder
public class MessageResponse {
String responseMessage;
}
我的孩子类看起来像这样:
@Getter
@Setter
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuperBuilder
public class ListResponse extends MessageResponse {
List<Item> itemList;
int itemCount;
}
其中Item是一个Serializable
类。
最初ListResponse
是
itemList = null
itemCount = 0
responseMessage = null
当我尝试使用构建器构建ListResponse
,它根本不会更改ListResponse
对象。 我正在尝试构建为
//listResponse is @Autowired from Spring and is initially as shown above.
List<Item> itemList = getItems(); // It returns a list of 15 items, i have checked in debugger, It does.
listResponse.builder()
.bucketList(itemList)
.responseMessage("Item List.")
.bucketCount(itemList.size())
.build();
即使在执行listResponse
.build()
之后,这个listResponse
对象的内容仍然是(null, 0 , null)
。
我试图搜索有关@SuperBuilder
和@Builder
其他参考资料,但没有结果。 有人可以指出这里出了什么问题吗?
构建器总是创建一个新实例。 这是构建器模式的目的,也是构建器的工作方式,无论您使用 Lombok 的@SuperBuilder
、 @Builder
还是手动构建器实现。
您可以看到builder()
方法是一个static
方法,因此它无法访问该实例(通常您的 IDE 应该在这里给您一个警告,建议改为编写ListResponse.builder()
)。
如果要使用预先填充现有实例中的字段的构建器创建新实例,则可以使用toBuilder = true
作为@(Super)Builder
上的注释参数。 然后调用listResponse.toBuilder()
。
如果要修改实例,构建器模式不是正确的选择。 改用二传手。 这些也可以由 Lombok 以流畅、可链接的方式生成; 有关详细信息,请参阅@Accessors
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.