在从第三方库扩展的类上使用Lombok的@SuperBuilder概念

问题描述 投票:1回答:1

我具有如下的类层次结构。

孩子->父母->超级父母

由于Child类扩展了[[Parent类,因此我必须使用Lombok的@SuperBuilder注释而不是@Builder。而且,据我所知,所有超类都需要具有@SuperBuilder批注。但就我而言,SuperParent类来自外部库,我无法在其中添加@SuperBuilder批注。我收到以下编译错误。

The constructor SuperParent(DocumentUploadedResponseDto.DocumentUploadedResponseDtoBuilder<capture#1-of ?,capture#2-of ?>) is undefined.
任何解决方案或替代方案?谢谢。
spring-boot lombok
1个回答
0
投票
这很丑,但是有可能。您必须在ParentSuperParent之间的继承链中插入一个助手类;我们称它为SuperParentBuilderEnabler。在此类中,您必须手动实现所有必要的构建器元素。特别是,您必须为SuperParent中的字段编写所有设置方法。这将允许ParentChild类仅使用@SuperBuilder批注,而无需进行任何进一步的修改。

我假设SuperParent有一个int superParentField字段,只是为了演示如何在builder类中编写这样的setter方法。此外,我假设可以通过构造函数参数设置此字段。这是您必须要做的:

public abstract class SuperParentBuilderEnabler extends SuperParent { public static abstract class SuperParentBuilderEnablerBuilder<C extends SuperParentBuilderEnabler, B extends SuperParentBuilderEnablerBuilder<C, B>> { private int superParentField; public B superParentField(int superParentField) { this.superParentField = superParentField; return self(); } protected abstract B self(); public abstract C build(); } protected SuperParentBuilderEnabler(SuperParentBuilderEnablerBuilder<?, ?> b) { super(b.superParentField); } }

现在让Parent extend SuperParentBuilderEnabler完成。
© www.soinside.com 2019 - 2024. All rights reserved.