Why should one use Objects.requireNonNull()?

2020-01-30 02:29发布

I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object (argument) is null.

public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}

But NullPointerException will be thrown anyway if a null object is dereferenced. So, why should one do this extra null check and throw NullPointerException?

One obvious answer (or benefit) is that it makes code more readable and I agree. I'm keen to know any other reasons for using Objects.requireNonNull() in the beginning of the method.

7条回答
叛逆
2楼-- · 2020-01-30 03:19

The basic usage is checking and throwing NullPointerException immediately.

One better alternative (shortcut) to cater to the same requirement is @NonNull annotation by lombok.

查看更多
登录 后发表回答