【问题标题】:Lombok @Wither Inheritance (super-/sub- classes)Lombok @Wither 继承(超/子类)
【发布时间】:2019-06-25 19:46:39
【问题描述】:

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

我有一个抽象类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;
}

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

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

【问题讨论】:

    标签: java lombok


    【解决方案1】:

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

    所以在生成Child的代码时,Lombok并不知道Parent继承了哪些wither方法。因此,它无法从Parent 生成抽象withA() 的实现。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 2021-06-18
      相关资源
      最近更新 更多