28.8.2023

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)
   }
}
Simon

Softwareentwickler

Zur Übersicht

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund