Project Lombok - @NonNull Annotation Example

Adding @NonNull annotation to attributes makes our constructor check for nullability and throw NullPointerExceptions accordingly. So we can use @NonNull on the parameter of a method or constructor to have Lombok generate a null-check statement for us.

Without Project Lombok

Without Project Lombok, we need to add a piece of code to handle null pointer exception:
package net.javaguides.lombok.nonnull;

import net.javaguides.lombok.User;

public class NonNullExample {
    private String name;

    public NonNullExample(User user) {
        if (user == null) {
            throw new NullPointerException("person is marked @NonNull but is null");
        }
        this.name = user.getFirstName();
    }

    public static void main(String[] args) {
        NonNullExample example = new NonNullExample(null);
    }
}

With Project Lombok

With Project Lombok, we are not writing any code to handle null pointer null but we are just adding @NonNull annotation:
package net.javaguides.lombok.nonnull;

import lombok.NonNull;
import net.javaguides.lombok.User;

public class NonNullLombokExample {
    private String name;

    public NonNullLombokExample(@NonNull User person) {
        this.name = person.getFirstName();
    }

    public static void main(String[] args) {
        NonNullLombokExample example = new NonNullLombokExample(null);
    }
}

Reference

GitHub Repository

You can view the source code of this article on my GitHub repository at https://github.com/RameshMF/project-lombok-tutorial

Comments