1. Overview

It is important to include null checks into both generated and handwritten methods.

In this tutorial, we'll look at the Lombok @NonNull annotation which helps us in this matter.

2. Use @NonNull on Methods and Constructors

When we use the @NonNull annotation on a method, Lombok adds a null check to the beginning of the method. For constructors, the null check is added after the super() or this() call.

We'll use the EmployeeService class:

public class EmployeeService {

    public void increaseSalary(@NonNull String name) {
        System.out.println(name);
    }
}

Here, EmployeeService has the increaseSalary method. Then we're annotating the name parameter with @NonNull.

Let's see what Lombok injects into our method:

public class EmployeeService {

    public void increaseSalary(String name) {
        if (name == null) {
            throw new NullPointerException("name is marked @NonNull but is null");
        }

        System.out.println(name);
    }
}

We see that Lombok puts a null check at the beginning of the method. If the check fails, it throws a NullPointerException with the message saying "name is marked @NonNull but is null".

3. Use @NonNull on Instance Fields

We can also annotate instance fields with @NonNull. As a result, other Lombok annotations take this information into account. For example, @Setter generated methods include a null check. Additionally, @RequiredArgsConstructor treats @NonNull instance variables as it would treat to final variables.

Let's see an example using @NonNull and @Setter:

@Getter
@Setter
public class Company {

    @NonNull
    private String location;
}

Here, we're annotating the location field with @NonNull. Also, Company is annotated with @Getter and @Setter.

When Lombok generates the setter method for location, it must also use the information coming from @NonNull and put a null check:

public class Company {

    private String location;

    public String getLocation() {
        return this.location;
    }

    public void setLocation(String location) {
        if (location == null) {
            throw new NullPointerException("location is marked @NonNull but is null");
        }

        this.location = location;
    }
}

Here, Lombok indeed puts a null check on the setLocation method.

4. Summary

In this tutorial, we've explored the usage of the Lombok @NonNull annotation.

Finally, check out the source code over on Github.