Using @RequiredArgsConstructor and @NonNull annotation example

In this post under Lombok, I will explain with example what is the purpose of “@RequiredArgsConstructor” annotation and how to use it with “@NonNull” annotation.

This annotation is applied at the class level and when applied it generates constructor with a parameter for each required fields.

Note: It will also add a parameter for non-initialized final fields also.

For example if our goal is to create the below Person class

Person

public class Person {
    private String firstName;
    private String middleName;
    private String lastName;
    private float salary;

    public Person(String firstName, String middleName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.middleName = middleName;
    }
}

In the above class, we have added a Person constructor with three parameter for each instance variable firstName, middleName, and lastName.

We can get this constructor automatically generated by using “@RequiredArgsConstructor” and “@NonNull” annotation as shown below

Modified Person class

package package18;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.ToString;

@ToString
@RequiredArgsConstructor
public class Person {
    @NonNull
    private String firstName;
    @NonNull
    private String middleName;
    @NonNull
    private String lastName;
    private float salary;
}

As shown in the above code, I have applied “@RequiredArgsConstructor” at the class level and “@NonNull” to each field except “salary” field because it is not a required field.

The Lombok will generate a constructor with one parameter for each “@NonNull” annotated field.

In this way we can use “@RequiredArgsConstructor” and “@NonNull” annotation to generate a constructor with a parameter for each required fields.

Below is the main class showing the call made to automatically generated constructor with argument.

Main class

package package18;

public class Example18 {
    public static void main(String[] args) {
        Person person1 = new Person("Ellis", "M", "Robertson");
        System.out.println(person1);
    }
}

Here we are creating a “Person” object by calling the automatically generated required argument constructor.

Below is the output

Output

    Person(firstName=Ellis, middleName=M, lastName=Robertson, salary=0.0)

Leave a Reply