Friday, December 9, 2022

10 Examples Of Lombok Libarary In Java

Hello guys, if you are working in Java then you may have heard about Lombok, one of the popular Java library which alleviate pain Java developer by removing boiler plate code and provides improve development experience. Yes, Lombok can remove a lot of code like the one you put on equals() and hashCode, getter and setter, toString and constructor and much more. This means you can just create a Java class with fields much like Record of Java SE 17 and you can use it like a fully functional Java class, I mean you can create object using constructor or Builder and you can get and set values using gettter and setter, only difference is they are not visible in code. But then you may be thinking how does it work? Where does it get those getter and setter? why not compiler raise any problem?

Well, its all magic of bytecode manipulation and code generation. Lombok will always generate code with getter and setter so that compiler is happy but because those code are not visible in your source file it looks clean means developer or you is also happy, but you can see the methods in your IDE just like it shown below. 

This is like the win-win solution and that's why I love Lombok, so much that its not possible for me to code without it, until Record came in.

Anyway, this article is not about Record, which also provide similar benefit, not at the scale of Lombok but a lot of them. This article is about Lombok and how to effectively use Lombok by exploring its various feature through live examples. But, before we get to the 10 best examples that will teach you everything you need to know about Lombok in Java, let me tell you a little bit more about what it really is.

10 Examples Of Lombok Annotations In Java



 

10 Examples Of Project Lombok Annotations In Java

Right now, Java is one of the most popular programming languages in the world. Project Lombok is basically a Java library tool that can be used to minimize or even remove all the boilerplate code and thus make the developers' job easier during development. It can also be used to increase the readability of the source code, thus allowing you to save space. 

Another important thing that you need to keep in mind is that Lombok adds all these boilerplate codes at the time of compilation in the '.class' file and not in your source code. You can look at the following examples to get a better understanding of what Project Lombok is all about.

1. Java Without Lombok

This is a vivid example of Java without Lombok. It is a Java model class with four private fields as well as their getters, setters, no-args constructor, parameterized construct, and toString method. 



public class Employee {

	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;

	public Employee() {}

	public Employee(Integer employeeId, String name,
					String company, String emailId)
	{
		super();
		this.employeeId = employeeId;
		this.name = name;
		this.company = company;
		this.emailId = emailId;
	}

	public Integer getEmployeeId() { return employeeId; }

	public void setEmployeeId(Integer employeeId)
	{
		this.employeeId = employeeId;
	}

	public String getName() { return name; }

	public void setName(String name) { this.name = name; }

	public String getCompany() { return company; }

	public void setCompany(String company)
	{
		this.company = company;
	}

	public String getEmailId() { return emailId; }

	public void setEmailId(String emailId)
	{
		this.emailId = emailId;
	}

	@Override public String toString()
	{
		return "Employee ["
			+ "employeeId=" + employeeId + ", name=" + name
			+ ", "
			+ " company=" + company + ", emailId=" + emailId
			+ "]";
	}
}

2. Java With Lombok

Now you can look at the following example to see what difference Lombok makes to the same code that is given above. Please note that it is very easy and intuitive to use the Lombok annotations.

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Employee {
	private @Getter @Setter Integer employeeId;
	private @Getter @Setter String name;
	private @Getter @Setter String company;
	private @Getter @Setter String emailId;
}

As you can see, the difference is clearly visible. Whereas the first example contains almost 60 lines of code, the second example reduces it to around 20 lines without the help of Project Lombok. It also increases the readability and maintainability of the source code. 



3. Configuring Lombok To Eclipse

You can easily download the Lombok install file from the official site. Open the file to start the installation. You need to specify a location and select the IDE. Click on the install button to complete the installation. 
Finally, you can verify the installation by going to the Eclipse IDE Help section. 

4. Lombok Annotations: @Getter and @Setter

Lombok gives you a specific set of annotations that will make your coding life easier. These annotations will give you the getter and setter methods for a specified field. It can also be used at both levels. 
The Getter annotation will generate a getter method along with an access type that will simply return the field. 
The Setter annotation will generate a setter method along with an access type that is public which returns void. 

import lombok.Getter;
import lombok.Setter;

public class Employee {
	private @Getter @Setter Integer employeeId;
	private @Getter @Setter String name;
	private @Getter @Setter String company;
	private @Getter @Setter String emailId;
}

10 Examples Of Lombok In Java


5. Lombok The @NoArgsConstructor Example

This annotation can be used to generate a constructor with no arguments. It basically does not do anything and has an empty body. It is commonly used in combination with other parameterized constructors. You can generate an object of a specific class by passing no arguments into the constructor. 

import lombok.NoArgsConstructor;

@NoArgsConstructor
public class Employee {
	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;
}

6. Lombok @AllArgsConstructor Example

This annotation will generate a parameterized constructor that will accept a single parameter for each field. It will then initialize them using the parameter. You can use it to generate an object of the class by passing the initial values of the field into the constructor. 

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class Employee {
	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;
}

7. Lombok @ToString Example 

You can use this annotation to override the toString() method as well as generate a default implementation. It will print the class name and the fields in that order. 

import lombok.ToString;

@ToString
public class Employee {
	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;
}



8. Lombok @EqualsAndHashCode Example

This annotation will override the equals() and hashCode() methods as well as provide a defalut implementation. This default implementation will make use of all the non-static fields.

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class Employee {
	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;
}


9. Lombok @Data Example

You can use this annotation as basically a shortcut annotation that bundles all of the other annotations like @EqualsAndHashCode, @ToString, @Getter, and @Setter into a single annotation. It will give you all the commonly used boilerplate code in the model classes of Java. 

import lombok.Data;

@Data
public class Employee {
	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;
}


10. Lombok @Builder Example

This annotation can be used to remove all the boilerplate code that is involved in setting properties for an object. You can set the properties of an object with a single statement of code and also make it readable and clean. 

import lombok.Builder;

@Builder
public class Employee {
	private Integer employeeId;
	private String name;
	private String company;
	private String emailId;
}



That's all about Lombok library in Java. It's one of my favorite Java library as it help you to write clean code and improves developer productivity. I highly recommend every Java developer to learn Lombok and there is no better way to learn then using Lombok in your project. You can start using Lombok by following these examples until you get comfortable. All modern IDE like Eclipse and IntelliJIDEA support Lombok, so you can use Lombok classes just like any other regular class in Java. 


Other Java Coding tutorials you may like
  • 5 Free Courses to learn Object Oriented Programming (courses)
  • How to use Factory method design pattern in Java? (tutorial)
  • Difference between Factory and Dependency Injection Pattern? (answer)
  • 5 Free Courses to learn Data Structure and Algorithms (courses)
  • When to use Command Design Pattern in Java (example)
  • Difference between Factory and Abstract Factory Pattern? (example)
  • 7 Best Courses to learn Design Pattern in Java (courses)
  • How to create thread-safe Singleton in Java (example)
  • 18 Java Design Pattern Interview Questions with Answers (list)
  • How to use Template Design Pattern in Java? (template pattern)
  • 7 Best Books to learn the Design Pattern in Java? (books)
  • How to implement the Strategy Design Pattern in Java? (example)
  • Difference between State and Strategy Design Pattern in Java? (answer)
  • 20 System Design Interview Questions (list)
  • 10 OOP Design Principle Every Java developer should learn (solid principle)
  • How to implement a Decorator design pattern in Java? (tutorial)
  • 7 Books to learn System Design for Beginners (System design books)
  • How to design a Vending Machine in Java? (questions)
  • How to use Composite Design Pattern in Java (composite example)

Thanks a lot for reading this article so far. If you like this example and tutorial of Lombok library in Java then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are an experienced Java developer and want to master design pattern to write better code then you can also checkout this list of best design pattern courses for experience developers to start with. It contains great online courses to learn design pattern and how to use them in real world coding.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.