Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the Lombok @Builder passing the parent class as parameter?

Tags:

I want to create a new Child instance passing a Parent and other additional parameters.

For example if I have:

public class Parent {
    public String param1;
    public String param2;
    // many parameters
    public String paramN;
}

public class Child extends Parent {
    public String subValue;
}

With lombok, is there a builder that lets me create a Child instance passing the Parent and the missing value as parameters?

Would be easier if I could write something like:

Parent p = Parent.builder()
                 .param1("a")
                 .param2("b")
                 // many parameters
                 .paramN("b")
                 .build();
Child c = Child.builder(p).subValue("c").build();
like image 995
freedev Avatar asked Mar 24 '21 14:03

freedev


People also ask

What does @builder in Lombok do?

@Builder(access = AccessLevel. PACKAGE) is legal (and will generate the builder class, the builder method, etc with the indicated access level) starting with lombok v1.

What is difference between @builder and @SuperBuilder?

The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.

How do you use super builder?

Install the Builder Theme on your Super site Click on the Theme you have selected to use. You'll see a box with the 'code' you need to copy and install on your Super site. Go to super.so and open the site where you are adding the theme. In the Builder template on your notion site, select and copy the code snippet.

Is SuperBuilder still experimental?

Solving this problem is probably possible but seems at first glance quite costly compared to the noise it aims to kill. Especially knowing that “SuperBuilder” is still considered as an experimental feature.


1 Answers

Other answers don't truly make your client code simply reuse the parent instance you already have. But this is doable. You have two options:

The hard one is to write your custom annotation that does what you want. You can even make it generic so that it works for any classes the have parent/child hierarchy. Have a look at this example. If you feel brave you can raise a feature request on Lombok's github page.

Option two would be to write your custom builder for the child. See example here. In your custom builder in the init step you would be reading a passed in Parent instance, and setup the inherited fields only.

like image 94
Evdzhan Mustafa Avatar answered Oct 11 '22 20:10

Evdzhan Mustafa