Lombok @Wither/@With Inheritance(超/子类)

And*_*kyi 7 java lombok

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

我有一个抽象类Parent和具体类ChildChild应该是不可变的。两者都戴上@Wither会给我两个错误:

  • 构造函数 Child(String) 未定义
  • Child 类型必须实现继承的抽象方法 Parent.withA(String)
@Value
@Wither
@NonFinal
@SuperBuilder
abstract class Parent {
    String a;
}

@Value
@Wither
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
class Child extends Parent {
    String b;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Jan*_*eke 9

Lombok 是一个注释处理器。它们在每个编译单元(即Java 文件)上运行,并且无法访问其他编译单元的信息。Parent这意味着 Lombok在处理时无法了解有关类内容的任何信息Child

因此,在生成 的代码时Child,Lombok 不知道从 继承哪些 wither 方法ParentwithA()因此,它无法生成来自的抽象的实现Parent

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

长话短说:@Wither不适用于继承。我建议仅将其放在Parent并手动实施Child

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