Using @AllArgsConstructor annotation example

In this post under Lombok, I will explain the purpose of “@AllArgsConstructor” annotation and how to use it.

This annotation when added at class level, automatically creates a constructor with all the fields present in the class.

If a field is annotated with “@NonNull” annotation, the automatically generated constructor code will add a null check for that field in the constructor.

Below is a source code which shows how to use it

Person

package package19;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.ToString;

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

Below is the main code, that shows the constructor calls.

Main class

1  package package19;
2  
3  public class Example19 {
4      public static void main(String[] args) {
5          Person person1 = new Person("Ellis", "M", "Robertson", 1000.50f);
6          System.out.println(person1);
7          
8          person1 = new Person("Ellis", "M", null, 1000.50f);
9          System.out.println(person1);
10         
11         person1 = new Person(null, "M", null, 1000.50f);
12         System.out.println(person1);
13     }
14 }

In the above code, first constructor call at line 5, we have provided all the arguments. So an object will be created

Second constructor call at line 8, we have set “middleName” argument to null, still an object is created because it is not required.

Third constructor call at line 11, we have set “firstName” argument to null, this will throw NullPointerException as it is a required field.

In this way we can use “@AllArgsConstructor” annotation.

Below is the output

Output

Person(firstName=Ellis, middleName=M, lastName=Robertson, salary=1000.5)
Person(firstName=Ellis, middleName=M, lastName=null, salary=1000.5)
Exception in thread "main" 
java.lang.NullPointerException: firstName is marked non-null but is null
    at LombokConcepts/package19.Person.<init>(Person.java:7)
    at LombokConcepts/package19.Example19.main(Example19.java:11)

Leave a Reply