OneCompiler

How Project Lombok simplifies the java code

290

Introduction

  1. In Java, We will create POJO classes, but for each POJO we need to create constructors, setters, getters. Of course we can use IDE to generate those constructors and methods, but still our java class looks very big with non business logic code.

  2. But by using Project Lombok no need to create any constructors, setters, getters explicitly, It will create at compile time.

  3. Project Lambok Provide so many annotations, just use those annotations and simplify your java code.

Normal Java code

package com.oc;

import java.util.Date;

public class User {

	private long userId;
	private String userName;
	private Date dob;

	public long getUserId() {
		return this.userId;
	}

	public void setUserId(long argUserId) {
		this.userId = argUserId;
	}

	public String getUserName() {
		return this.userName;
	}

	public void setUserName(String argUserName) {
		this.userName = argUserName;
	}

	public User(long argUserId, String argUserName, Date argDob) {
		super();
		this.userId = argUserId;
		this.userName = argUserName;
		this.dob = argDob;
	}

	public Date getDob() {
		return this.dob;
	}

	public void setDob(Date argDob) {
		this.dob = argDob;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((this.dob == null) ? 0 : this.dob.hashCode());
		result = prime * result + (int) (this.userId ^ (this.userId >>> 32));
		result = prime * result + ((this.userName == null) ? 0 : this.userName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (this.dob == null) {
			if (other.dob != null)
				return false;
		} else if (!this.dob.equals(other.dob))
			return false;
		if (this.userId != other.userId)
			return false;
		if (this.userName == null) {
			if (other.userName != null)
				return false;
		} else if (!this.userName.equals(other.userName))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "User [userId=" + this.userId + ", userName=" + this.userName + ", dob=" + this.dob + "]";
	}

}

  • Above java code is simple User POJO class but it looks very nasty.

Java code using Lambok

package com.oc;

import java.util.Date;
import lombok.Data;

@Data
public class User {
	private long userId;
	private String userName;
	private Date dob;
}

  • Above java code is using lambok annotation, in compile time it will create the setters, getters, constructors so we can call those methodes from any class.

Note: By using Project Lambok we can create common code dynamically at compile time so no need to write unnecessary code in java.