Reduce Boilerplate Code in your Java applications with Project Lombok
One of the most frequently voiced criticisms of the Java programming language is the amount of Boilerplate Code it requires. This is especially true for simple classes that should do nothing more than store a few values. You need getters and setters for these values, maybe you also need a constructor, overriding equals() and
hashcode() is often required and maybe you want a more useful toString() implementation. In the end you might have 100 lines of code that could be rewritten with 10 lines of Scala or Groovy code. Java IDEs like Eclipse or IntelliJ try to reduce this problem by providing various types of code generation functionality. However, even if you do not have to write the code yourself, you always see it (and get distracted by it) if you open such a file in your IDE.
Project Lombok (don’t be frightened by the ugly web page) is a small Java library that can help reducing the amount of Boilerplate Code in Java Applications. Project Lombok provides a set of annotations that are processed at development time to inject code into your Java application. The injected code is immediately available in your development environment.
Lets have a look at the following Eclipse Screenshot:
The defined class is annotated with Lombok’s @Data annotation and does not contain any more than three private fields. @Data automatically injects getters, setters (for non final fields), equals(), hashCode(), toString() and a constructor for initializing the final dateOfBirth field. As you can see the generated methods are directly available in Eclipse and shown in the Outline view.
Setup
To set up Lombok for your application you have to put lombok.jar to your classpath. If you are using Maven you just have to add to following dependency to your pom.xml:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.14.6</version> <scope>provided</scope> </dependency>
You also need to set up Lombok in the IDE you are using:
- NetBeans users just have to enable the Enable Annotation Processing in Editor option in their project properties (see: NetBeans instructions).
- Eclipse users can install Lombok by double clicking lombok.jar and following a quick installation wizard.
- For IntelliJ a Lombok Plugin is available.
Getting started
The @Data annotation shown in the introduction is actually a shortcut for various other Lombok annotations. Sometimes @Data does too much. In this case, you can fall back to more specific Lombok annotations that give you more flexibility.
Generating only getters and setters can be achieved with @Getter and @Setter:
@Getter @Setter public class Person { private final LocalDate birthday; private String firstName; private String lastName; public Person(LocalDate birthday) { this.birthday = birthday; } }
Note that getter methods for boolean fields are prefixed with is instead of get (e.g. isFoo() instead of getFoo()). If you only want to generate getters and setters for specific fields you can annotate these fields instead of the class.
Generating equals(), hashCode() and toString():
@EqualsAndHashCode @ToString public class Person { ... }
@EqualsAndHashCode and @ToString also have various properties that can be used to customize their behaviour:
@EqualsAndHashCode(exclude = {"firstName"}) @ToString(callSuper = true, of = {"firstName", "lastName"}) public class Person { ... }
Here the field firstName will not be considered by equals() and hashCode(). toString() will call super.toString() first and only consider firstName and lastName.
For constructor generation multiple annotations are available:
- @NoArgsConstructor generates a constructor that takes no arguments (default constructor).
- @RequiredArgsConstructor generates a constructor with one parameter for all non-initialized final fields.
- @AllArgsConstructor generates a constructor with one parameter for all fields in the class.
The @Data annotation is actually an often used shortcut for @ToString, @EqualsAndHashCode, @Getter, @Setter and @RequiredArgsConstructor.
If you prefer immutable classes you can use @Value instead of @Data:
@Value public class Person { LocalDate birthday; String firstName; String lastName; }
@Value is a shortcut for @ToString, @EqualsAndHashCode, @AllArgsConstructor, @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) and @Getter.
So, with @Value you get toString(), equals(), hashCode(), getters and a constructor with one parameter for each field. It also makes all fields private and final by default, so you do not have to add private or final modifiers.
Looking into Lombok’s experimental features
Besides the well supported annotations shown so far, Lombok has a couple of experimental features that can be found on the Experimental Features page.
One of these features I like in particular is the @Builder annotation, which provides an implementation of the Builder Pattern.
@Builder public class Person { private final LocalDate birthday; private String firstName; private String lastName; }
@Builder generates a static builder() method that returns a builder instance. This builder instance can be used to build an object of the class annotated with @Builder (here Person):
Person p = Person.builder() .birthday(LocalDate.of(1980, 10, 5)) .firstName("John") .lastName("Smith") .build();
By the way, if you wonder what this LocalDate class is, you should have a look at my blog post about the Java 8 date and time API!
Conclusion
Project Lombok injects generated methods, like getters and setters, based on annotations. It provides an easy way to significantly reduce the amount of Boilerplate code in Java applications.
Be aware that there is a downside: According to reddit comments (including a comment of the project author), Lombok has to rely on various hacks to get the job done. So, there is a chance that future JDK or IDE releases will break the functionality of project Lombok. On the other hand, these comments where made 5 years ago and Project Lombok is still actively maintained.
- You can find the source of Project Lombok on GitHub.
Reference: | Reduce Boilerplate Code in your Java applications with Project Lombok from our JCG partner Michael Scharhag at the mscharhag, Programming and Stuff blog. |
This actually replied my problem, thank you!