如何在@SuperBuilder上使用龙目岛的toBuilder

2022-09-04 02:20:16

目前我有这三个类:

@Value
@NonFinal
@SuperBuilder
public class Parent {
    // Some fields
}

@Value
@EqualsAndHashCode(callSuper = true)
@SuperBuilder(toBuilder = true)
public class ChildA extends Parent {
    // Some fields
}

@Value
@EqualsAndHashCode(callSuper = true)
@SuperBuilder(toBuilder = true)
public class ChildB extends Parent {
    // Some fields
}

我想在映射器中使用它,如下所示,以避免重复任何代码:

private ChildA buildChildA(Entity entity) {
    Parent parent = ((ChildB) buildParent(entity, ChildA.builder().build()))
        .toBuilder()
        // Populate Child A fields from entity
        .build();
}

private ChildB buildChildB(Entity entity) {
    Parent parent = ((ChildA) buildParent(entity, ChildA.builder().build()))
        .toBuilder()
        // Populate Child B fields from entity
        .build();
}

private Parent buildParent(Partner entity, Parent parent) {
    return parent.toBuilder()
        // Populate Parent fields here
        .build();
}

但是,当我尝试编译时,我得到:

ChildA.java:13: error: method does not override or implement a method from a supertype 
@SuperBuilder(toBuilder = true) 
^ 
ChildB.java:13: error: method does not override or implement a method from a supertype 
@SuperBuilder(toBuilder = true) 
^ 
2 errors

你如何将toBuilder与@SuperBuilder?我使用的是龙目岛v1.18.4。


答案 1

如果要与 一起使用,层次结构中的所有类都必须具有 。原因是该方法仅从其各自的类中复制字段值,而是将字段值从超类型复制到超类型的方法。@SuperBuildertoBuildertoBuilder=truetoBuilder()toBuilder()

因此,也可以添加到您的类中。toBuilder=trueParent


答案 2

推荐