google guava工具包 checkNotNull的作用 , checkState

checkNotNull 源码如下:

Preconditions.checkNotNull(object);

 
 
public static <T> T checkNotNull(T reference) {
  if (reference == null) {
    throw new NullPointerException();
  }
  return reference;
}
使用 checkNotNull 方法进行校验会抛空指针异常,还可以用自定义异常说明的方法

public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
  if (reference == null) {
    throw new NullPointerException(String.valueOf(errorMessage));
  }
  return reference;
}

目的是为了清晰的表达程序意图,并且精确控制出错的位置。

1. 尽早抛出异常
在方法的入口,或运算开始前,检查数据,而不是等到数据被传递到更深层的方法时被动的触发异常,有助于更精确的确定异常产生的原因。

2. 断言该变量非空
也就提醒了调用者,如果传入null肯定是错误的,直接去找为什么会是null的原因即可,不用再分析这里到底是要允许null,还是不允许null。

3. 更精确的知道哪个变量是null
被动抛出的NullPointerException只能定位到行,如果是类似于这种代码
xxxx.get(0).getAddress().equals(yyyy.getAddress()),你不容易看出到底是哪个变量或中间结果是null的,需要调试或输出一下数据才能确定。

在Java中任由代码对空变量进行操作而导致空指针异常是一种低级错误。

往往很多时候同一段代码不是一个人维护的 或者你需要在时隔很久后去维护它 这个时候谁也不知道改动这些代码会带来哪些隐形bug 对于空指针的检查可以让你在开发过程中提前避免很多因为改动代码带来的以外因素 让问题尽量在开发时暴露而不是上线后暴露


checkState(!(null == cookie || null == cookie.getValue()), "用户未登录");
public static void checkState(boolean expression, @Nullable Object errorMessage) {
  if (!expression) {
    throw new IllegalStateException(String.valueOf(errorMessage));
  }
}

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/80815165