Using @NonNull annotation

In this post under Lombok, I will show with example the purpose and how to use @NonNull annotation.

This annotation is applied at method or constructor parameter level.

This annotation adds a null check which will check whether the designated parameter value is null or not. If the parameter value is null it will throw NullPointerException.

Below is an example of how we can use the annotation


1  package package4;
2  
3  import lombok.Getter;
4  import lombok.NonNull;
5  import lombok.Setter;
6  
7  @Getter
8  @Setter
9  public class Person {
10     private String firstName;
11     private String middleName;
12     private String lastName;
13     
14     public Person(@NonNull String firstName, String middleName, @NonNull String lastName) {
15         super();
16         this.firstName = firstName;
17         this.middleName = middleName;
18         this.lastName = lastName;
19     }
20 }

In the above code, at line 14, we are marking “firstName” and “lastName” parameter with @NonNull annotation.

So Lombok will add a null check for these two parameters.

Below is the main class for your reference

Main Class


1  package package4;
2  
3  public class Example4 {
4      public static void main(String[] args) {
5          Person person = new Person("fName", null, "lName");
6          System.out.println(person.getFirstName() + ":" + person.getMiddleName() + ":" + person.getLastName());
7          System.out.println();
8          person = new Person(null, "mName", "lName");
9      }
10 }

In the above code, at line 5, we are creating a “Person” object. This will not thrown NullPointerException as all the required parameters have value.

At line 8, we are trying to create “Person” object with “firstName” parameter value being null. This time the code will throw NullPointerException as shown in the below output.

The parameter name which is null will be mentioned in the exception message.

Output


fName:null:lName

Exception in thread "main" java.lang.NullPointerException: firstName is marked non-null but is null
    at LombokConcepts/package4.Person.<init>(Person.java:14)
    at LombokConcepts/package4.Example4.main(Example4.java:8)

Leave a Reply