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")

代码实现区别不大,那么为啥不选择优雅^_^
 

最新文章

  1. Google C++单元测试框架GoogleTest---Google Mock简介--概念及基础语法
  2. JS数组经典冒泡排序
  3. Github上有趣的资料 | JS
  4. Theano3.4-练习之多层感知机
  5. android SDK manager 无法获取更新版本列表
  6. 如何垂直居中一个&lt;img&gt;?
  7. Entity Framework 安装出现问题
  8. 单片微机原理P2:80C51外部中断与定时器系统
  9. Haoop MapReduce 的Partition和reduce端的二次排序
  10. junit4X系列源码--Junit4 Runner以及test case执行顺序和源代码理解
  11. java I/O框架 (二)文件操作(File)
  12. UOJ#103. 【APIO2014】Palindromes PAM模板题
  13. HBuilder
  14. TCP流量控制
  15. js中时间大小的比较
  16. Js/Bind()的认识
  17. IT软件外包行业深入分析:现状、前途、趋势、待遇 什么是软件外包 外包公司是怎么工作的 软件外包公司的面试 软件外包公司需要什么样的人
  18. 查找SQL Server 自增ID值不连续记录
  19. GC 提前晋升
  20. awk统计文件中某关键词出现次数

热门文章

  1. ios获取软键盘完成事件
  2. 剑指offer---1、顺时针打印矩阵
  3. P1537 弹珠
  4. flutter 小知识
  5. jQuery 加载事件
  6. java.lang.Double.byteValue() 方法
  7. Jackson环境安装设置
  8. Feign 系列(05)Spring Cloud OpenFeign 源码解析
  9. js浮点数的计算总结
  10. extern static和函数