Jan 6 2020

POJOs Made Easy with Project Lombok

Every Java application has some sort of bean or Plain Old Java Object (POJO) to hold and manage state. Because of good Object Oriented Programming (OOP) principles we encapsulate field access with getter and setter methods. Most modern IDEs allow you to quickly create getters and getters. You can often find a Generate option under the Code menu from your favorite IDE. But generating getters and setters produces a lot of unnecessary boilerplate code.

With Project Lombok, you can reduce all that boilerplate getter and setter code with a few annotations.

The following bit of code will produce a Java class with the necessary getters and setters to access all the defined fields.

package com.juixe.core.pojo;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString @EqualsAndHashCode
@Getter @Setter
public class Person {
   private Long id;
   private String firstName;
   private String lastName;
}

Given the Person class above, you can start coding the following.

   Person p = new Person();
   p.setFirstName("Boingo");
   p.setLastName("API");
   p.setId(1000l);

The getter and setter methods are added to the bytecode for the Person class by Project Lombok through the annotations. If you remove one of the annotations, like the @Setter annotation, then the setters methods will be deleted.

We just saw how a few annotation can generate getters, setters, equals, hashCode, and toString methods for simple Java classes. If you want all these methods generated for you, automatically, you can just use the @Data annotation like the following.

package com.juixe.core.pojo;

import lombok.Data;

@Data
public class Person {
   private Long id;
   private String firstName;
   private String lastName;
}

There is also a @Value annotation that is similar to @Data except that it is intended for immutable objects, so it doesn’t generate any setter methods.