龙目岛@Wither 继承 (super-/sub- 类)

Lombok @Wither Inheritance (super-/sub- classes)

请建议在应用继承时如何使用 @Wither

我有抽象的classParent和具体的ChildChild 应该是不可变的。将 @Wither 放在两者上会给我两个错误:

@Value
@Wither
@NonFinal
@SuperBuilder
abstract class Parent {
    String a;
}

@Value
@Wither
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
class Child extends Parent {
    String b;
}

我很乐意删除 @Wither 并使用构建器方法,但我正在重构 public 库(尝试优化模型 classes)和我不希望我的客户出现编译错误。

我还发现这个问题解释了第二个错误。但是意图逻辑不清楚https://github.com/rzwitserloot/lombok/issues/945

Lombok 是一个注解处理器。每个编译单元(即 Java 文件)上的 运行 并且无法访问其他编译单元的信息。这意味着 Lombok 在处理 Child.

时无法知道 class Parent 的内容

所以在为Child生成代码时,Lombok并不知道从Parent继承了哪些凋零方法。因此,它无法从 Parent.

生成抽象 withA() 的实现

第二个问题是凋零方法需要一个构造函数,该构造函数将所有字段作为参数,包括来自 superclass 的字段。由于上述限制,这也不可能为 Lombok 生成。

长话短说:@Wither 不适用于继承。我建议只将它放在 Parent 上并为 Child.

手动实现它

另一种选择是将 @SuperBuilder(toBuilder=true) 放在两个 class 上,然后使用 instance.toBuilder().a("newValue").build().