简体   繁体   中英

Lombok builder inheritance with Complex Class Structure

I've read other questions regarding lombok's builder and inheritance but none of the solutions have worked. Using Lombok version 1.18.4 and Java 11.

I'm trying to inherit the parent builder while also satisfying an interface, using only immutable fields. This is my class structure:

The Code

public interface FooInterface {
    String getFoo();
}

The getFoo logic is very common across all implementations, so I decided to make an Abstract helper to avoid copy-pasting the same code everywhere.

@Data
@SuperBuilder
public abstract class AbstractFoo implements FooInterface {

    @Builder.Default
    private final String foo = "foo";

}

And the actual Foo implementation:

@Data
@SuperBuilder
public class FooTest extends AbstractFoo {
    private final String bar;
}

'Win Condition'

I would like Lombok to

  1. Recognize fields required by the parent class.
  2. Include those fields in the generated Builders of child classes.

In code:

final FooInterface fooTest = FooTest.builder.foo("string").bar("string").build();
assertThat("string").equals(fooTest.getFoo());
assertThat("string").equals(fooTest.getBar());

Attempted Solutions

The problem is, IntelliJ highlights the @Data annotation with this error:

Lombok needs a default constructor in the base class.

If I remove @Data from FooTest I get this error:

There is no default constructor available in base class .

So I removed the @SuperBuilder from AbstractFoo and added a manually-created constructor with all the arguments. The error persists. I've tried other things and annotation combinations, but none have worked.

I also tried -in vain- to set all AbstractFoo fields to protected final , and declare Foo implementations final themselves, which would be consistent with my business rules.

@SuperBuilder isn't supported by current version of IntelliJ IDEA plugin yet.

There's an open issue on project's Github tracker - https://github.com/mplushnikov/lombok-intellij-plugin/issues/513

Although it's targeted for 0.25 release which has been released just a few days ago - https://github.com/mplushnikov/lombok-intellij-plugin/releases/tag/releasebuild_0.25

Issue still seems to be open and not yet implemented.

I'd suggest to just try version 0.25 and wait for the next release if it won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM