Core Java

Lombok @RequiredArgsConstructor Annotation

Hello. In this tutorial, we will explore Java Lombok constructor annotation.

1. Introduction

Lombok is a popular Java library that simplifies the development process by automatically generating boilerplate code (such as getters, setters, constructors, etc.) for Java classes. The name “Lombok” is derived from the Indonesian island of Lombok.

Java developers often find themselves writing a lot of repetitive code for basic class functionality, which can be tedious and error-prone. Lombok helps reduce this boilerplate code by introducing annotations that instruct the compiler to generate the necessary code during compilation.

1.1 Advantages and Disadvantages of Lombok

1.1.1 Advantages

  • Reduces Boilerplate Code: Lombok eliminates the need to write repetitive and mundane code, such as getters, setters, constructors, and equals/hashCode methods. This leads to cleaner and more concise code.
  • Enhances Code Readability: With Lombok annotations, the class code becomes more focused on business logic, making it easier to read and understand.
  • Saves Development Time: Lombok helps developers save time by automating the generation of common code, allowing them to focus on writing more important aspects of the application.
  • Fewer Errors due to Manual Coding: As developers don’t need to manually write repetitive code, the chances of introducing bugs and errors due to manual coding are reduced.
  • Easy to Maintain and Update: Since Lombok-generated code is automatically kept in sync with changes to the class, maintenance, and updates become simpler.

1.1.2 Disadvantages

  • Dependency on External Library: When using Lombok, your project becomes dependent on the Lombok library. This could lead to issues if Lombok’s compatibility with the development environment or future versions becomes a concern.
  • Limited Control over Code Generation: While Lombok simplifies code generation, it might not cater to all custom scenarios. This could limit the developer’s control over how the code is generated.
  • Potential Learning Curve for Beginners: For developers new to Lombok, there might be a learning curve in understanding the various annotations and their usage.
  • IDE Support and Annotation Processors: Some IDEs might not fully support Lombok’s annotations, which could lead to reduced IDE code assistance and error highlighting.
  • Compatibility with Third-Party Tools and Plugins: Lombok-generated code might not always play well with other third-party tools, libraries, or plugins, potentially causing conflicts or unexpected behavior.

1.2 Setup

Setting up Lombok in a Java project involves a few simple steps. Here’s a step-by-step guide to getting started with Lombok:

1.2.1 Add Lombok Dependency to Your Build Tool

For Maven, add the Lombok dependency to your project’s pom.xml file:

pom.xml

<dependencies>
       <!-- Other dependencies -->
       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <version>1.18.20</version> <!-- Replace with the latest version available -->
           <scope>provided</scope>
       </dependency>
   </dependencies>

For Gradle, add the following line to your build.gradle file:

build.gradle

dependencies {
       // Other dependencies
       compileOnly 'org.projectlombok:lombok:1.18.20' // Replace with the latest version available
}

1.2.2 Enable Annotation Processing

Lombok uses annotation processing to generate the code during compilation. To enable annotation processing, follow these steps based on your IDE:

1.2.2.1 Eclipse
  • Download the Lombok JAR from the official website: https://projectlombok.org/download
    • Double-click the downloaded JAR to install it. Select your Eclipse IDE location.
    • Restart Eclipse.
1.2.2.2 IntelliJ IDEA
  • Install the “Lombok” plugin from the IntelliJ plugin marketplace.
    • After installing the plugin, enable annotation processing:
      • Go to Preferences/Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors.
      • Check “Enable annotation processing” and “Obtain processors from project classpath.”

1.2.3 Start Using Lombok Annotations

You can now use Lombok annotations in your Java classes to eliminate boilerplate code. Some common annotations include:

  • @Getter and @Setter: Automatically generate getter and setter methods for fields.
  • @ToString: Generate a toString() method for the class.
  • @EqualsAndHashCode: Generate equals() and hashCode() methods for object comparison.
  • @NoArgsConstructor, @RequiredArgsConstructor, and @AllArgsConstructor: Generate constructors with different configurations.
  • @Data: Combines @Getter, @Setter, @EqualsAndHashCode, @ToString, and @RequiredArgsConstructor in a single annotation.
  • @Builder: Generate a builder pattern for the class.

Simply add the relevant annotation to your class, and Lombok will handle the code generation during compilation.

1.2.4 Compile and Run

Once you’ve added the Lombok annotations and enabled annotation processing, you can compile and run your Java project as usual. The Lombok-generated code will be automatically added to your classes during the compilation process.

Remember to always use the appropriate Lombok annotations for your specific use case, and make sure your IDE is properly configured to support Lombok’s annotation processing.

2. Java Lombok Constructor Annotation Example

The @RequiredArgsConstructor is a Lombok annotation in Java that generates a constructor for a class with parameters for all final fields in the class. It does not generate a constructor for non-final fields. This can be useful when you have immutable classes with final fields, as it automatically creates a constructor to initialize these fields. Here’s an example of how to use @RequiredArgsConstructor:

Person.java

package com.jcg.example;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class Person {
    private final String name;
    private final int age;
    private final String address;

    // Other methods and fields can be added as needed
}

In the above example, we have a Person class with three private final fields: name, age, and address. By applying the @RequiredArgsConstructor annotation to the class, Lombok will automatically generate the following constructor:

Explanation snippet

public Person(String name, int age, String address) {
    this.name = name;
    this.age = age;
    this.address = address;
}

As you can see, the generated constructor takes in three parameters corresponding to the three final fields of the class and initializes them accordingly. With @RequiredArgsConstructor, you don’t need to write the constructor manually, making your code cleaner and reducing boilerplate code for immutable classes.

2.1 Usage of example

The above example demonstrates the usage of Lombok’s @RequiredArgsConstructor annotation to simplify the creation of constructors for classes with final fields. By using this annotation, you can avoid writing the constructor manually and let Lombok generate it for you. Let’s see how you can use the `Person` class with the @RequiredArgsConstructor annotation:

Main.java

public class Main {
    public static void main(String[] args) {
        // Create a new Person object using the generated constructor
        Person person1 = new Person("John Doe", 30, "123 Main Street");

        // Print the details of the person
        System.out.println("Name: " + person1.getName());
        System.out.println("Age: " + person1.getAge());
        System.out.println("Address: " + person1.getAddress());
    }
}

In this example, we create a Person object named person1 using the generated constructor from the @RequiredArgsConstructor annotation. We pass values for the three final fields: name, age, and address while creating the object.

Example output

Name: John Doe
Age: 30
Address: 123 Main Street

3. Conclusion

In conclusion, the Lombok @RequiredArgsConstructor annotation is a powerful tool that simplifies the process of creating constructors for Java classes with final fields. By applying this annotation to a class, developers can avoid writing boilerplate code for constructors that initialize final fields. Lombok automatically generates the constructor, taking into account all the final fields in the class, and makes it easy to instantiate objects with the required data.

The @RequiredArgsConstructor annotation is particularly useful for classes designed to be immutable, where final fields are commonly used to ensure the object’s state remains unchanged after instantiation. It promotes the use of final fields, contributing to more reliable and maintainable code.

Furthermore, by using @RequiredArgsConstructor, developers can ensure that all required fields are initialized at object creation, preventing potential NullPointerExceptions or accidental null assignments. This leads to more robust code and reduces the chances of runtime errors related to uninitialized variables.

Overall, the Lombok @RequiredArgsConstructor annotation streamlines the creation of constructors for classes with final fields, eliminating the need for repetitive and error-prone code. It enhances code readability, promotes immutability, and contributes to a more efficient and concise development process. However, it is essential to use this annotation judiciously and consider the overall design and requirements of the class to fully leverage its benefits.

This concludes our tutorial, and I trust that the article provided you with the information you sought. I wish you happy learning and encourage you to share your newfound knowledge with others! You can download the source code from the Downloads section.

4. Download the Files

This was a tutorial to explore Lombok @RequiredArgsConstructor annotation in Java.

Download
You can download the files of this example here: Lombok’s @RequiredArgsConstructor Annotation

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button