我具有如下的类层次结构。
孩子->父母->超级父母
由于Child类扩展了[[Parent类,因此我必须使用Lombok的@SuperBuilder
注释而不是@Builder
。而且,据我所知,所有超类都需要具有@SuperBuilder
批注。但就我而言,SuperParent类来自外部库,我无法在其中添加@SuperBuilder
批注。我收到以下编译错误。
The constructor SuperParent(DocumentUploadedResponseDto.DocumentUploadedResponseDtoBuilder<capture#1-of ?,capture#2-of ?>) is undefined.
任何解决方案或替代方案?谢谢。
Parent
和SuperParent
之间的继承链中插入一个助手类;我们称它为SuperParentBuilderEnabler
。在此类中,您必须手动实现所有必要的构建器元素。特别是,您必须为SuperParent
中的字段编写所有设置方法。这将允许Parent
和Child
类仅使用@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
完成。