Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lombok @SuperBuilder annotation with toBuilder on an abstract class?

Tags:

java

lombok

I have the following classes:

@SuperBuilder(toBuilder = true)
public abstract class Parent {
    //...
}

@SuperBuilder(toBuilder = true)
public class Child extends Parent {
    //...
}

@SuperBuilder(toBuilder = true)
public class Child2 extends Parent {
    //...
}

Why am I unable to call toBuilder() on an instance of the abstract class (Parent) as shown in the following code?

public copy(Parent parent) {
    parent.toBuilder().build();
}
like image 763
Hossein Nasr Avatar asked Jan 26 '23 02:01

Hossein Nasr


1 Answers

In fact, as Hossein Nasr already explained, Lombok cannot know whether there are subclasses that do not have toBuilder=true.

Lombok could require all direct subclasses of an abstract class to also use toBuilder by adding an abstract toBuilder() method on the abstract class. However, there may be use-cases where subclasses should not have a toBuilder (although I haven't seen any good examples of those). Furthermore, indirect subclasses may still lack the toBuilder feature. Therefore, lombok does not enforce toBuilder on subclasses of abstract classes.

Good news is that you can easily work around it in your case (only direct subclasses) by adding the abstract toBuilder() method to your abstract class Parent manually:

@SuperBuilder(toBuilder = true)
public abstract class Parent {
    public abstract ParentBuilder<?, ?> toBuilder();
}

With this change, your copy method compiles and works as expected.

If you also have indirect subclasses, you have to find other means to ensure they also have @SuperBuilder(toBuilder = true). If those would not have this annotation, you may experience strange behavior (e.g. calling copy() will instantiate a different class).

Disclaimer: I implemented the @SuperBuilder feature.

like image 79
Jan Rieke Avatar answered Jan 27 '23 15:01

Jan Rieke