为什么要使用 Objects.requireNonNull()? [英] Why should one use Objects.requireNonNull()?

查看:49
本文介绍了为什么要使用 Objects.requireNonNull()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Oracle JDK 中的许多 Java 8 方法使用 Objects.requireNonNull(),如果给定的对象(参数)是 ,它会在内部抛出 NullPointerExceptionnull.

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;
}

但是如果 null 对象被取消引用,无论如何都会抛出 NullPointerException.那么,为什么要进行这个额外的空检查并抛出NullPointerException?

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

一个明显的答案(或好处)是它使代码更具可读性,我同意.我很想知道使用的任何其他原因Objects.requireNonNull() 在方法的开头.

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;
  }

或更短:

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

现在您知道:

  • 使用 new() 成功创建 Foo 对象时
  • 那么它的bar字段保证非空.
  • when a Foo object was successfully created using new()
  • then its bar field is guaranteed be non-null.

将其与:您今天创建一个 Foo 对象,明天您调用一个使用该字段并抛出的方法.很可能,明天您将不知道为什么该引用在 昨天 传递给构造函数时为 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!

主要优点是:

  • 如前所述,控制行为
  • 更容易调试 - 因为你在创建对象的上下文中抛出异常.在某个时间点,您的日志/跟踪很有可能会告诉您出了什么问题!
  • 如上所示:这个想法的真正力量与 final 字段一起展现.因为现在您班级中的任何其他代码都可以安全地假设 bar 不为空 - 因此您不需要任何 if (bar == null) 在其他地方检查!
  • 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!

这篇关于为什么要使用 Objects.requireNonNull()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆