Wouldn’t it be great to have one annotation for getting rid of all boilerplate code in model and entity classes?

Let's start with this simple model class, which only contains a few fields:

/**
* my model class with fields.
*/
public class MyModelClass {
private boolean someBoolean;
private String someStringField;
private float someExcludedField;
}

If you follow full mandatory guidelines of the Java standard and guidelines, you will need to implement this additional code:

  • a no argument constructor
  • an all field as argument constructor
  • getters for all fields
  • setters for all fields
  • a human usable toString method
  • an equals method to fulfill the object identity requirements in Java
  • a hashCode method to fulfill the object identity requirements in Java

You will end up with a huge class, just like described in the article What is boilerplate code and the boilerplate meaning in Java? 

1. Project Lombok

Wouldn’t it be great if we had a way to avoid all those repetitive lines of code in each class? Boilerplate code is usually seen in Objected Oriented Programming, where we have to deal with creating getters, setters, toString(), and other necessary methods for the identity handling of an object. Some smart guys have seen this annoying issue and created a nice and neat Java library, which helps us to avoid redundant and useless code. They named it Project Lombok. Project Lombok is a lightweight Java library, which deals with common and advanced isses with repetitive code. Lombok uses annotations to substitute mandatory and repetitive code with clean, meaningful code. It removes unnecessary code while still fullfiling repetitive requirements, which leaves you with easily readable powerful code.

With Lombok @Data annotation you can keep your code nice and short as in the code sample above. At the same time, all important methods (getters, setters, toString, etc.) will be automatically implemented for you.

/**
* my model class with fields.
*/ @Data
public class MyModelClass {
private boolean someBoolean;
private String someStringField;
private float someExcludedField;
}

Looks interesting, doesn't it? So let us describe how to use Project Lombok for your projects.

1.1. Installing Project Lombok into your preferred IDE

The first step is to get the latest version of Project Lombok from here. The download is a simple .jar file which can be easily integrated in the following most common Java IDEs:

  1. Eclipse
  2. NetBeans
  3. IntelliJ

1.1.1. Lombok Eclipse

To get Lombok up and running with your Eclipse IDE, double click on the ‘lombok.jar’ file you just downloaded. If no window appears run the jar file from the command line by moving to the folder of your downloaded jar file and running

java -jar lombok.jar

This will lead you to an installation window for Eclipse Lombok installation. From here, the installer typically automatically detects your Eclipse installation. If it doesn’t, you can manually navigate the installer to your Eclipse executable and then simply click on ‘Install/Update’ button. The executables are named:

  • Windows:
    eclipse.exe
  • Mac:
    eclipse
  • Linux:
    eclipse

1.1.2. Lombok NetBeans

To use Lombok annotations within NetBeans, simply add ‘lombok.jar’ to your project library. After that, right-click on your project and go to

  • Project Properties> Build > Compiling
  • From this window, enable the checkbox saying, ‘Enable Annotation Processing in Editor’

1.1.3. Lombok IntelliJ

To add Lombok to your IntelliJ IDE, you will have to download the IntelliJ plugin for Lombok from here.
From your IDE,

  • go to File> Settings > Plugins.
  • From there, click on ‘Browse repositories’ and search for the plugin you just downloaded
  • Click on ‘Install Plugin’

1.2. Start Using Lombok

Project Lombok makes use of annotations to get rid of repetitive code. Here’s a list of some common and useful Lombok annotations:

  • @Data
    Lombok @Data generates the methods toString(), equals() and hashcode() along with the more important getters and setters in Java and also the required default constructor for your object.
  • @Getter
    Lombok @Getter generates getters for your class.
  • @Setter
    Lombok @Setter generates setters for your class.
  • @ToString
    Lombok @ToString generates a human readable toString() method for your class.

The use of these annotations will be demonstrated below. We will use simple POJOs (Plain Old Java Objects) for our demonstration, as that is what Lombok works with.

2. Lombok @Data annotation

The Lombok @Data annotation does everything needed to create a Java class except for the object declaration itself. When used within a class, the @Data annotation automatically creates getters and setters for all fields, a human usable toString() method, and an equals() and hashCode() method to fulfill the object identity requirements in Java. Moreover, it also generates a constructor for the object, which takes in final fields as its parameters.
Here’s the @Data annotation in action:

//Using the @Data Lombok Annotation 
@Data
public class Car {
   private final Person owner;
   private String manufacturer;
   private final int registrationNumber;
}

If we delombok this class - to see how the class would look like if we'd implement it manually - it would look like this: 

//Simple Car object 
public class Car {
//car will have an owner of type ‘Person’
private Person owner;
private String manufacturer;
private int registrationNumber;

public String getManufacturer() {
return manufacturer;
}

public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}

public Person getOwner() {
return owner;
}

public int getRegistrationNumber() {
return registrationNumber;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((manufacturer == null) ? 0 : manufacturer.hashCode());
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result + registrationNumber;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarExtended other = (CarExtended) obj;
if (manufacturer == null) {
if (other.manufacturer != null)
return false;
} else if (!manufacturer.equals(other.manufacturer))
return false;
if (owner == null) {
if (other.owner != null)
return false;
} else if (!owner.equals(other.owner))
return false;
if (registrationNumber != other.registrationNumber)
return false;
return true;
}
}

We can clearly see how using the Lombok @Data annotation helped us avoid writing an additional repetitive boilerplate code!

3. Lombok @Getter and @Setter annotation

As the names suggest, these annotations can be used to generate getters and setters without the need to write them yourself. All you need to do is use the annotations and Lombok will do the rest for you! You can also set the access level of the generated methods by using optional parameters as used below.

//Using the @Getter and @Setter together will generate both methods for the field
@Getter @Setter
private boolean booked = true;
@Setter(AccessLevel.PROTECTED)
private String manufacturer;

And the same code snippet without Lombok:

//boolean to see whether car is booked or not
private boolean booked = true;
private String manufacturer;

public boolean isBooked() {
return booked;
}

public void setBooked (final boolean booked) {
this.booked = booked;
}

protected void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}

Here we also do not need to discuss which code looks more compact.

4. Lombok @toString annotation

The Lombok @toString annotation generates a human readable toString() method with name-value pairs of non-static fields of your class. Moreover, you can exclude some fields from the toString() method by passing relevant arguments, and on top of that you can also remove field names from the toString() output by setting the parameter ‘includeFieldName‘ to ‘false’. Other than that, you can also include the toString() method of your super class to be included in the generated method. Here is a Lombok example snippet for @toString:

@ToString(exclude="someExcludedField")
public class Person {
   private String lastName;
   private String lastName;
}

And the same without Lombok:

//A Very Simple Person Class with a toString method
public class Person {
   private String lastName;
   private String firstName;

   @java.lang.Override
   public java.lang.String toString() {
      return "First Name: " + firstName+ "," +  "Last Name:" + lastName;
   }
}

As you can see it is worth to check out Project Lombok and all of its annotations since it helps you to get rid of a lot of "crappy" and repetitive boilerplate code.