Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Project Lombok: Reduce Boilerplate Code

DZone's Guide to

Project Lombok: Reduce Boilerplate Code

Lombok is a fantastic time saver, but it can be troublesome to use with Java 10. Let's work through the problems to get it working.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

In this post, we will take a look at Project Lombok and what it has to offer us. Project Lombok reduces boilerplate code by making use of annotations in your code. The main advantage is achieved with POJOs (Plain Old Java Objects): You don't have to code getters and setters anymore. Although your IDE provides the possibility to generate getters and setters, with Project Lombok, you also don't have to read them anymore. The source code used in this post can be found at GitHub.

Create the Project

Let's start by creating a Maven project. I am using IntelliJ IDEA Community Edition 2018.1 for this and will make use of Java 10. I am using Java 10 in order to see whether we can already make use of Project Lombok with Java 10.

We create a main class, Application, which will just print a Hello Lombok message to the console:

public class Application {
    public static void main(String...args) {
        System.out.println("Hello Lombok");
    }
}


In order to use Project Lombok, we first need to add it as a dependency to our POM file:

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>


According to the instructions on the website of Project Lombok, we need to use the edge version if we want to make use of modules in our project. The edge version is, however, not available in a snapshot directory and, therefore, you need to download it and add it to your project. We add the JAR file to the lib directory and update our POM accordingly:

<dependency> 
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/lombok-edge.jar</systemPath>
</dependency>


Next, we need to add the lombok module to our module-info.java file:

module com.mydeveloperplanet.mylombokplanet {
    requires static lombok;
}


So far, so good, except that IntelliJ keeps complaining that module lombok cannot be found. Restarting IntelliJ did not solve the problem. It seems that Project Lombok is not yet ready to be used with Java Modules and it is better to wait until all the issues are resolved and the edge version is officially released. In order to continue, we will disable the module-info.java by renaming it to module-info.java_.  Besides this, it seems that there are also Java 10-related issues with Lombok.

Lombok IDE IntelliJ Plugin

In order to have first-class support for Lombok in IntelliJ, it is advised to install the Lombok IDE IntelliJ plugin. This way, IntelliJ can recognize the generated getters and setters for code completion.

  • Go to 'File - Settings... - Plugins'
  • Click 'Browse Repositories' and search for 'Lombok'
  • Install the 'IntelliJ Lombok Plugin', at the time of writing we install version v0.17-2018.1

For some reason, I had to install it twice. After the first attempt, an error was shown indicating that the plugin ZIP file was not available. The second attempt was successful and the plugin was installed on my system.

In order to finalize the installation, it is also necessary to enable annotation processing in IntelliJ. Go to 'File - Settings... - Build, Execution, Deployment - Compiler - Annotation Processors' and check 'Enable annotation processing'.

POJO and @Data

Now let's see what Lombok has to offer us. We create a Car POJO with some String attributes. Normally seen, we are going to create the getters and setters by means of our IDE. The disadvantage of this approach is that a lot of boilerplate code is created which we inevitably will read. And here Lombok comes to the rescue! We import lombok.Data and add the @Data annotation to the POJO.

@Data
public class Car {
    private String brand;
    private String numberOfWheels;
    private String engineType;
}


This results in the creation of getters, setters, equalshashCode and the toString method as can be seen in the figure below.

car_lombok

Other Annotations

Let's take a look at some other useful Lombok annotations. First, we create a CarOther POJO. Instead of using the @Data annotation, we use the @Getter in order to generate only the getter for the specified attribute and we use the @Setter in order to generate only the setter for the specified attribute. This gives us the opportunity to differentiate for which attributes getters and setters are created.

public class CarOther {
    @Getter private String brand;
    @Setter private String numberOfWheels;
    private String engineType;
    private boolean hybrid;
}


In IntelliJ, we see that only setNumberOfWheels and getBrand are generated by Lombok.

CarOther_lombok

By means of the ToString annotation, it is possible to restrict which attributes are shown in the toString method. We can do so by defining which attributes need to be excluded from the toString method. In the example below, we exclude engineType and hybrid.

@ToString(exclude = {"engineType", "hybrid"})
public class CarOther {
    ...
}


In order to test this, we add the following to our main method of the Application class. This way, we can test the difference between the two toString methods.

System.out.println("Car as string is " + new Car());
System.out.println("CarOther as string is " + new CarOther());


When we build and run the application, our output is the following, exactly what we expected.

Car as string is Car(brand=null, numberOfWheels=null, engineType=null)
CarOther as string is CarOther(brand=null, numberOfWheels=null)


Something similar can be done with the annotation equalsAndHashcode, but then it applies to the equals and hashCode methods.

A complete list with generated Java code can be found at the Lombok website.

Lombok and Java

Wouldn't it be great when the Lombok annotations made it to standard Java? Yes it would, but it doesn't seem to be happening in the near future. The creators of Lombok have already tried to insert far less ambitious changes into Java and are quite disappointed with that experience. The responses can be found at https://github.com/rzwitserloot/lombok/issues/1312 and at https://groups.google.com/forum/#!topic/project-lombok/6sggfRp0PUY . So, for the time being, you will need to include Lombok in your project when you want to use it.

Summary

In this post, we have shown how you can use Project Lombok with Java 10, which is not yet very easy to do. My advice is to use Java 8 when using Project Lombok up to the moment that the edge version has become a stable release. If you do insist on using Java 10, then you will need to use the edge version, but disable Java Modules because of the issues with it.

We also have taken a look at some features that can be easily applied to your daily work and will speed up development and reduce boilerplate code.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java 10 ,lombok ,java ,boilerplate code ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}