Project Lombok Annotations Examples

In this article, we will discuss all the Project Lombok annotations with an example.

Lombok is a library used for reducing the boilerplate code from Java source code.

Boilerplate code is a typical source code that cannot be omitted by the language specification. Basically, the boilerplate code does not have a specific logic hence it becomes redundant code in implementation.

Following are the typical Boilerplate source code in Java language.
  • getter/setter methods for accessing the member variables
  • equals/hashCode methods
  • toString methods
  • Constructors
  • Closing process of resources (input and output stream, etc.)
  • Generation of the logger instance
In Lombok, the boilerplate code gets generated at the time of compilation thereby providing a mechanism to remove the redundant code from the source code developed by the developer.

All Project Lombok Annotations with Examples

Below are all the annotations provided by Project Lombok. I explained each Lombok annotation step by step in my separate articles.

1. Project Lombok - @NonNull Annotation - In this post, we use @NonNull annotation on the parameter of a method or constructor to have Lombok generate a null-check statement for us.

2. Project Lombok - @Getter, @Setter, @NoArgsConstructor, @RequiredArgsConstructor, and @AllArgsConstructor - In this post, we will see how to reduce getter, setter and constructor boilerplate code using Lombok annotations.

3. Project Lombok - toString(), equals() and hashCode() Annotations - In this post, I will show you how to generate the toString()equals() and hashCode() automatically in Java projects using Project Lombok annotations - @ToString@EqualsAndHashCode.

4. Project Lombok - @Data Annotation - In this post, I will show you how to reduce boilerplate code for the below methods using @Data annotation.
  1. getters for all fields
  2. setters for all non-final fields,
  3. toString method
  4. equals and hashCode implementations that involve the fields of the class
  5. constructor that initializes all final fields
5. Project Lombok - Builder Pattern using @Builder Annotation - In this post, I will show you how to reduce the boilerplate code of complex builder APIs.

6. Project Lombok - Logging @Slf4j Annotation - In this post, we will learn how to do blogging using Lombok annotations.

7. Project Lombok - Automatic Resource Management using @Cleanup - In this post, We use Project Lombok provided a @Cleanup annotation to ensure a given resource is automatically cleaned up before the code execution path exits your current scope.

8. Project Lombok - @Synchronized Annotation In this example, we will see how to use @Synchronized annotation to make Java methods synchronized.

Check out the Lombok official documentation to know more about Lombok annotations at https://projectlombok.org/features/all.

Comments