Objects.requireNonNull(T obj, String message)定制你的NPE(空指针)异常

在IDEA跟踪源码时多次碰到Objects.requireNonNull方法,该方法用于提早判断对象是否为空并抛出NPE。小组开发强调程序健壮性,不允许代码出现明显NPE,常需写判空逻辑并抛出自定义异常,还将展示其具体源码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IDEA中习惯跟踪源码实现逻辑,多次碰到Objects.requireNonNull(T obj)这个方法,改方法主要用于提早判断对象是否为空,以便更早的抛出NPE

平时小组开发中强调程序健壮性,不允许组员的代码中出现明显的NPE,这样多数时候都要写判空逻辑,抛出自定义的异常

我们看下具体的源码:

/**
 * Checks that the specified object reference is not {@code null}.
 * This method is designed primarily for doing parameter validation in methods
 * and constructors, as demonstrated below:
 * <blockquote><pre>
 * public Foo(Bar bar) {
 *     this.bar = Objects.requireNonNull(bar);
 * }
 * </pre></blockquote>
 *
 * @param obj the object reference to check for nullity
 * @param <T> the type of the reference
 * @return {@code obj} if not {@code null}
 * @throws NullPointerException if {@code obj} is {@code null}
 */
public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}
解释:检查定义的对象引用不为空。设计该方法主要用来做方法和构造函数中的参数校验
如上,如果直接使用仍然是抛出一个NPE,除了能提早检测和抛出异常,无法直接在业务中使用

继续往下滚动,发现还有这个方法
/**
 * Checks that the specified object reference is not {@code null} and
 * throws a customized {@link NullPointerException} if it is. This method
 * is designed primarily for doing parameter validation in methods and
 * constructors with multiple parameters, as demonstrated below:
 * <blockquote><pre>
 * public Foo(Bar bar, Baz baz) {
 *     this.bar = Objects.requireNonNull(bar, "bar must not be null");
 *     this.baz = Objects.requireNonNull(baz, "baz must not be null");
 * }
 * </pre></blockquote>
 *
 * @param obj     the object reference to check for nullity
 * @param message detail message to be used in the event that a {@code
 *                NullPointerException} is thrown
 * @param <T> the type of the reference
 * @return {@code obj} if not {@code null}
 * @throws NullPointerException if {@code obj} is {@code null}
 */
public static <T> T requireNonNull(T obj, String message) {
    if (obj == null)
        throw new NullPointerException(message);
    return obj;
}

and throws a customized {@link NullPointerException} if it is:定制的空指针异常

and constructors with multiple parameters :多参数的构造函数

这样,下次我们想抛出一个自定义的空指针异常的时候,以前是:
if(obj==null){
  throw new xxxException("该记录不存在xxxx");
}
现在可以更优雅的写Objects.requireNonNull(T obj,"该记录不存在xxxx")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值