29.7.2020 |

Add Custom lombok Builder Methods

Lombok offers a Builder annotation to generate a builder for an existing class. By default only properties of the orginal class be used for the builder, but you can also add a custom builder if you want to add more complex objects.

Using Default lombok.Builder Methods:

@lombok.Builder
public class Developer {
   private String street;
   private String zip;
   private String city;

   Developer(Address address) {
      this.street = address.getStreet();
      this.zip = address.getZip();
      this.city = address.getCity();
   }

   //...

   public doBuild() {
      Developer.builder()
         .street(...)
         .zip(...)
         .city(...)
   }
}

Create Custom lombok.Builder Methods:

@lombok.Builder
public class Developer {
   private String street;
   private String zip;
   private String city;

   // Just create a Custom Builder class within the Class and only implement the custom Methods
   public static class DeveloperBuilder {
      
        public DeveloperBuilder address(Address address) {
            this.street = address.getStreet();
            this.zip = address.getZip();
            this.city = address.getCity();
           
            return this;
        }   
   }
   
   //...

   public doBuild() {
      Developer.builder()
         .address(address)
   }
}
Zur Übersicht
Simon Jakubowski

Mehr vom Devsquad...

Jörg Herbst

Join PDF with MacOS Preview Application

Umut Tufanoglu

Showcase Tool Capsize

Hallo, ich bin Jörg Herbst!

Ich bin der CEO von newcubator und freue mich über jede Nachricht!

* Pflichtfeld