LoginSignup
3
4

More than 5 years have passed since last update.

Lombokの@builderで親クラスも含めたい場合

Posted at

https://stackoverflow.com/questions/44948858/lombok-builder-on-a-class-that-extends-another-class のコードをまんまコピペ。@Builderはクラスに付けることが多いが、コンストラクタに付与してそこに親子両方のパラメータを列挙する、という回避案が書かれている。

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>
@AllArgsConstructor
@ToString
public class Parent {
      private double d;
      private float e;
}
@ToString(callSuper=true)
public class Child extends Parent  {
      private String a;
      private int b;
      private boolean c;

      @Builder
      public Child(String a, int b, boolean c, double d, float e) {
        super(d, e);
        this.a = a;
        this.b = b;
        this.c = c;
      }
}
Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build();
System.out.println(child);
Child(super=Parent(d=10.1, e=20.0), a=aVal, b=1000, c=true)
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4