Eliminate Boilerplate Java code with Lombok
I’ve been writing a lot of boilerplate Java code, lately — getters, setters, hashCode, equals and toString. Actually, I’d use Eclipse to generate these methods. There were some minor annoyances though, like when I needed to add a new member variable and then I had to regenerate code to include it.
It wasn’t pretty, but I had made my peace with it. Until I got to a class that had a lot of fields and I needed a builder to construct it. For those unfamiliar with the builder design pattern, here’s a quick primer. In a nutshell, I wanted to be able to write code like this:
User u = User.builder()
.name("Superman")
.realName("Kal-el")
.fakeName("Clark Kent")
.home("Krypton").build();
Unfortunately, Eclipse doesn’t generate these builder classes and I sure as hell wasn’t going to write them by hand. So, I did what all developers do and headed to StackOverflow and stumbled upon this thread that mentioned Project Lombok. Project Lombok generates boilerplate code for you based on annotations. All I needed to do was to write the Java class like this:
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
@Data class User {
private String name;
private String realName;
private String fakeName;
private String home;
};
The Data annotation generates getters, setters, hashCode, equals, toString and the Builder annotation generates the builder class. That’s it! I just followed the instructions on the Project Lombok website and was able to use it in my project in 10 mins.