Java Lombok @Builder 继承解决方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31664098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:23:04  来源:igfitidea点击:

Lombok @Builder inheritance workaround

javalombok

提问by Vivek Goel

Lombok @Builder doesn't work for inheritance use cases:

Lombok @Builder 不适用于继承用例:

For example

例如

class Foo{
 protected int xyz1;
 .....
 protected String xyz7;
}


class Bar extends Foo{

}

For given use case Lombok will not be able to generate methods to set value of parameter defined in Foo class.

对于给定的用例,Lombok 将无法生成方法来设置 Foo 类中定义的参数值。

A workaround for this is:

对此的解决方法是:

  1. Manual creating constructor of Bar.
  2. Putting a Builder annotation on that constructor.
  1. 手动创建 Bar 的构造函数。
  2. 在该构造函数上放置 Builder 注释。

Is there a better workaround ?

有更好的解决方法吗?

回答by fd8s0

I leave this here for reference, as other answers demonstrate there is now (not at the time this answer was posted) a @SuperBuilder feature available now in the library which seems more fitting.

我将其留在这里以供参考,因为其他答案表明现在(不是在发布此答案时)库中现在提供了一个 @SuperBuilder 功能,这似乎更合适。

It′s a bit hidden, but people have had this question before, see:

这有点隐蔽,但人们以前有过这个问题,请参阅:

https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/

https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/

To summarise the blog post

总结博客文章

@AllArgsConstructor
public class Parent {
  private String a;
}

public class Child extends Parent {

  private String b;

  @Builder
  private Child(String a, String b){
    super(a);
    this.b = b;
  }
}

Would allow you to use

会让你使用

Child.builder().a("testA").b("testB").build()

回答by Jacques Koorts

There is a solution to this problem currently in the works. Check the progress here: https://github.com/rzwitserloot/lombok/pull/1337

目前正在解决这个问题。在此处查看进度:https: //github.com/rzwitserloot/lombok/pull/1337

回答by Amit Kaneria

Lombok has introduced experimental features with version: 1.18.2 for inheritance issues faced with Builder annotation, and can be resolved with @SuperBuilder annotation as below.

Lombok 已经在 version: 1.18.2 中引入了实验性功能,用于解决 Builder 注解面临的继承问题,可以使用 @SuperBuilder 注解解决,如下所示。

@SuperBuilder
public class ParentClass {
    private final String a;
    private final String b;
}

@SuperBuilder
public class ChildClass extends ParentClass{
    private final String c;
}

Now, one can use Builder class as below (that was not possible with @Builder annotation)

现在,可以使用如下的 Builder 类(@Builder 注释无法实现)

ChildClass.builder().a("testA").b("testB").c("testC").build();