如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常
2024-10-07 17:42:23
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")
代码实现区别不大,那么为啥不选择优雅^_^
最新文章
- Google C++单元测试框架GoogleTest---Google Mock简介--概念及基础语法
- JS数组经典冒泡排序
- Github上有趣的资料 | JS
- Theano3.4-练习之多层感知机
- android SDK manager 无法获取更新版本列表
- 如何垂直居中一个<;img>;?
- Entity Framework 安装出现问题
- 单片微机原理P2:80C51外部中断与定时器系统
- Haoop MapReduce 的Partition和reduce端的二次排序
- junit4X系列源码--Junit4 Runner以及test case执行顺序和源代码理解
- java I/O框架 (二)文件操作(File)
- UOJ#103. 【APIO2014】Palindromes PAM模板题
- HBuilder
- TCP流量控制
- js中时间大小的比较
- Js/Bind()的认识
- IT软件外包行业深入分析:现状、前途、趋势、待遇 什么是软件外包 外包公司是怎么工作的 软件外包公司的面试 软件外包公司需要什么样的人
- 查找SQL Server 自增ID值不连续记录
- GC 提前晋升
- awk统计文件中某关键词出现次数