Project Lombok's @Builder annotation

We’ve been using Project Lombok for a long time to reduce boilerplate code in our Java projects – it provides you with a number of annotations (@NoArgsConstructor, @AllArgsConstructor, @Getter, etc.) that will be used to generate code for you. If you don’t know it yet, I recommend you take a look and adopt its usage.

In order to guarantee immutablity of our domain objects, we’ve also been keen to use the builder pattern. Implementing it for a lot of classes however is a prime candidate for generating a lot of boilerplate code. Unfortunately Lombok didn’t have a feature for auto generating builders when we started with our current project. Instead, we’ve been using another library, Michael Karneim’s PojoBuilder, that provided this functionality.

Since some time, the experimental features of Lombok contained a @Builder annotation and in January 2015 it got promoted to the official release. Last week I finally had a look at this new feature and it works pretty well. Once you add the @Builder annotation to your class, Lombok will create an inner builder class with methods for populating the builder’s fields and for creating pojo instances from it. You instantiate a builder by calling a static builder() method on the pojo’s class.

In contrast to Lombok’s approach, PojoBuilder creates a new class alongside the pojo class. In order to make the pojo’s fields visible to the builder, you had to expose them on a package visibility level – this always annoyed me a bit. Lombok, by creating an inner class, doesn’t require exposing class members.

One thing I did at first miss with Lombok’s Builder implementation was the ability to prepopulate a builder from an existing instance. Michael Karneim’s library had an option to create a copy() method for this. After some digging in Lombok’s forum I found this solution, which enables a very flexible approach to solve this problem:

@Builder
public class Pojo {
    private String name;
}

public static PojoBuilder builderFrom(Pojo toCopy) {
    return builder().name(toCopy.name);
}

While it would be nice to have this method autogenerated by Lombok, this approach works well for us. Especially because we don’t need it on every object anyway.
The PojoBuilder library did a great job in the recent years, but with this addition to Lombok we’ll probably abandon it over time.

UPDATE:
In the meantime @Builder got an attribute @Builder(toBuilder = true) that will generate a toBuilder() object method. As the name suggests, it will return a builder that is prepopulated with the values of the respective instance.

2 thoughts on “Project Lombok's @Builder annotation

Comments are closed.