Project Lombok – A Java Library to Reduce Boilerplate Code

All Java projects, be it small or a big enterprise mission critical project, it needs  POJOs. These classes form your model, beans, entities etc. When we deal with POJO, we need to have getters, setters, tostring and other Object specific methods implemented. Now as your project grows in size, you end up having lots of boilerplate code in your java code. In this article, we will look at one such library Project Lombok, which helps to reduce this kind of code.

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. With this library, you never write another getter or equals method again.

Adding Lombok to your IDE:

Usually, it will be as simple as adding a dependency to your pom file.

But sometimes, IDE fails to recognize this jar in order to process your Java files for syntactical analysis. In such a scenario, you have to make your IDE aware of this jar manually.

First, download the lombok.jar file from the Official location

Go to the folder where you have downloaded the jar and run below command

This command will prompt a window and will ask for IDE path, as shown in below

Lombok Setup

Specify the folder of your IDE and click Install/Update. This will copy the jar to eclipse folder (in case of your IDE is Eclipse). Then you will see below screen

Lombok Setup Complete

Post this, you need to restart your IDE.

Lombok annotations:

Now you have all required jars in your project and your IDE is also aware of them. Let us see some useful annotations to reduce your code.

@Data

This annotation will make sure that your java class gets default constructor, getter method on all fields, a setter on all non-final fields. It will also add toString, equals and hashcode method.

 

@Getter and @Setter

If you do not need all the convenience provided by @Data and want to keep more control of code flow, you can use individual annotations to provide getter and setter for your class variables.

The generated getter/setter method will be public unless you explicitly specify an AccessLevel

@ToString

While debugging if you need to look at your class state, you generally write a pretty toString method.  If you add @ToString to your class, you will get the required toString method automatically. Moreover, you can even tell Lombok if you need to exclude any variable.

@Log

You put this annotation on your class and a logger variable will be made available for you to use.

Conclusion

The Project Lombok is very useful when you have too many POJOs in your project. You can write readable code with less boilerplating.

Add a Comment

Your email address will not be published. Required fields are marked *