Javaexercise.com

Lombok Introduction In Java

Lombok is a java based library that is used to assist developer to create Software applications.

It automatically writes the boilerplate code such as getters, setters and toString method for the POJO.

It reduces the developement time and effort.

To use the Lombok library, you either can download it from the official site or use the below dependency for the maven project. 

Maven Dependency for the Lombok

Add this XML code to the pom.xml file of your maven project and update the project. 

<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.18.24</version>
		<scope>provided</scope>
</dependency>

After adding above depedency, you don't need to create setter and getters for your POJO class.

Let's see an example.

Creating Java code using Lombok in Java

Here, we used @Getter and @Setter annotations to instruct to the lombok to create getters and setters for us.

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Employee {

	private int id;
	private String name;
	private String email;	
	
}

See, we did not create any setter and getter for this class but instead used the annoations.

Calling/Accessing Setter and Getter methods

Now, we created an object of the Employee class and call its getter and setter method that are created by the Lombok annoations.

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Employee employee = new Employee();
		
		// Calling Setters
		employee.setId(001);
		employee.setName("rohan");
		employee.setEmail("[email protected]");
		
		// Calling Getters
		int id       = employee.getId();
		String name  = employee.getName();
		String email = employee.getEmail();
		
		System.out.println(id);
		System.out.println(name);
		System.out.println(email);
	}

}

Output:

1
rohan
[email protected]
 

This is the beauty of Lombok. It provides several annoations and tools to create automatic code to reduce time and effort.