如何在@SuperBuilder上使用Lombok的toBuilder

时间:2019-01-15 11:00:26

标签: java builder lombok

目前我有以下三个课程:

@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一起使用?我正在使用lombok v1.18.4。

1 个答案:

答案 0 :(得分:1)

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

所以也只需将toBuilder=true添加到您的Parent类中。