java requirenonnull,为什么要使用Objects.requireNonNull()?

Why should one use Objects.requireNonNull() ?

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 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.

解决方案

Because you can make things explicit by doing so. Like:

public class Foo {

private final Bar bar;

public Foo(Bar bar) {

Objects.requireNonNull(bar, "bar must not be null");

this.bar = bar;

}

Or shorter:

this.bar = Objects.requireNonNull(bar, "bar must not be null");

Now you know:

when a Foo object was successfully created using new()

then its bar field is guaranteed be non-null.

Compare that to: you create a Foo object today, and tomorrow you invoke a method that uses that field and throws. Most likely, you will not know tomorrow why that reference was null yesterday when it got passed to the constructor!

In other words: by explicitly using this method to check incoming references you can control the point in time when the exception will be thrown. And most of the time, you want to fail as fast as possible!

The major advantages are:

as said, controlled behavior

easier debugging - because you throw up in the context of the object creation. At a point in time where you have a certain chance that your logs/traces tell you what went wrong!

and as shown above: the true power of this idea unfolds in conjunction with final fields. Because now any other code in your class can safely assume that bar isn't null - and thus you do not need any if (bar == null) checks in other places!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值