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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With