**


《手册》的第 7 页和 25 页有两段关于空指针的描述 1:

  1. 【强制】Object 的 equals 方法容易抛空指针异常,应使用常量或确定有值
  2. 的对象来调用 equals。
  3. 【推荐】防止 NPE,是程序员的基本修养,注意 NPE 产生的场景:
  4. 返回类型为基本数据类型,return 包装数据类型的对象时,自动拆箱有可能产生
  5. NPE。
  6. 反例:public int f () { return Integer 对象}, 如果为 null,
  7. 自动解箱抛 NPE。数据库的查询结果可能为 null。
  8. 集合里的元素即使 isNotEmpty,取出的数据元素也可能为 null。
  9. 远程调用返回对象时,一律要求进行空指针判断,防止 NPE。
  10. 对于 Session 中获取的数据,建议进行 NPE 检查,避免空指针。
  11. 级联调用 obj.getA ().getB ().getC (); 一连串调用,易产生 NPE。


《手册》对空指针常见的原因和基本的避免空指针异常的方式给了介绍,非常有参考价值。
那么我们思考以下几个问题:

  • 如何学习
  1. NullPointerException


(简称为 NPE)?

  • 哪些用法可能造 NPE 相关的 BUG?
  • 在业务开发中作为接口提供者和使用者如何更有效地避免空指针呢?

    **

**


前面介绍过源码是学习的一个重要途径,我们一起看看

  1. NullPointerException


的源码:

  1. /**
  2. * Thrown when an application attempts to use {@code null} in a
  3. * case where an object is required. These include:
  4. * <ul>
  5. * <li>Calling the instance method of a {@code null} object.
  6. * <li>Accessing or modifying the field of a {@code null} object.
  7. * <li>Taking the length of {@code null} as if it were an array.
  8. * <li>Accessing or modifying the slots of {@code null} as if it
  9. * were an array.
  10. * <li>Throwing {@code null} as if it were a {@code Throwable}
  11. * value.
  12. * </ul>
  13. * <p>
  14. * Applications should throw instances of this class to indicate
  15. * other illegal uses of the {@code null} object.
  16. *
  17. * {@code NullPointerException} objects may be constructed by the
  18. * virtual machine as if {@linkplain Throwable#Throwable(String,
  19. * Throwable, boolean, boolean) suppression were disabled and/or the
  20. * stack trace was not writable}.
  21. *
  22. * @author unascribed
  23. * @since JDK1.0
  24. */
  25. public
  26. class NullPointerException extends RuntimeException {
  27. private static final long serialVersionUID = 5162710183389028792L;
  28. /**
  29. * Constructs a {@code NullPointerException} with no detail message.
  30. */
  31. public NullPointerException() {
  32. super();
  33. }
  34. /**
  35. * Constructs a {@code NullPointerException} with the specified
  36. * detail message.
  37. *
  38. * @param s the detail message.
  39. */
  40. public NullPointerException(String s) {
  41. super(s);
  42. }
  43. }

源码注释给出了非常详尽地解释:
空指针发生的原因是应用需要一个对象时却传入了

  1. null


,包含以下几种情况:

  1. 调用 null 对象的实例方法。
  2. 访问或者修改 null 对象的属性。
  3. 获取值为 null 的数组的长度。
  4. 访问或者修改值为 null 的二维数组的列时。
  5. 把 null 当做 Throwable 对象抛出时。


实际编写代码时,产生空指针的原因都是这些情况或者这些情况的变种。
《手册》中的另外一处描述
“集合里的元素即使 isNotEmpty,取出的数据元素也可能为

  1. null


。”

和第 4 条非常类似。
如《手册》中的:
“级联调用 obj.getA ().getB ().getC (); 一连串调用,易产生 NPE。”

和第 1 条很类似,因为每一层都可能得到

  1. null


。
当遇到《手册》中和源码注释中所描述的这些场景时,要注意预防空指针。
另外通过读源码注释我们还得到了 “意外发现”,JVM 也可能会通过

  1. Throwable#Throwable(String, Throwable, boolean, boolean)


构造函数来构造

  1. NullPointerException


对象。

**


通过源码可以看到 NPE 继承自

  1. RuntimeException


我们可以通过 IDEA 的 “Java Class Diagram” 来查看类的继承体系。
08 空指针引发的血案 - 图2
可以清晰地看到 NPE 继承自

  1. RuntimeException


,另外我们选取

  1. NoSuchFieldException


和

  1. NoSuchFieldError


和

  1. NoClassDefFoundError


,可以看到

  1. Throwable


的子类型包括

  1. Error


和

  1. Exception


, 其中 NPE 又是

  1. Exception


的子类。
那么为什么

  1. Exception


和

  1. Error


有什么区别?

  1. Excption


又分为哪些类型呢?
我们可以分别去

  1. java.lang.Exception


和

  1. java.lang.Error


的源码注释中寻找答案。
通过

  1. Exception


的源码注释我们了解到,

  1. Exception


分为两类一种是非受检异常(uncheked exceptions)即

  1. java.lang.RuntimeException


以及其子类;而受检异常(checked exceptions)的抛出需要再普通函数或构造方法上通过

  1. throws


声明。
通过

  1. java.lang.Error


的源码注释我们了解到,

  1. Error


代表严重的问题,不应该被程序

  1. try-catch


。编译时异常检测时,

  1. Error


也被视为不可检异常(uncheked exceptions)。
大家可以在 IDEA 中分别查看

  1. Exception


和

  1. Error


的子类,了解自己开发中常遇到的异常都属于哪个分类。
我们还可以通过《JLS》2 第 11 章 Exceptions 对异常进行学习。
其中在异常的类型这里,讲到:
不可检异常( unchecked exception)包括运行时异常和 error 类。
可检异常( checked exception )不属于不可检异常的所有异常都是可检异常。除 RuntimeException 和其子类,以及 Error 类以及其子类外的其他 Throwable 的子类。

08 空指针引发的血案 - 图3
还有更多关于异常的详细描述,,包括异常的原因、异步异常、异常的编译时检查等,大家可以自己进一步学习。

**

**


  1. @Test
  2. public void test() {
  3. Assertions.assertThrows(NullPointerException.class, () -> {
  4. List<UserDTO> users = new ArrayList<>();
  5. users.add(new UserDTO(1L, 3));
  6. users.add(new UserDTO(2L, null));
  7. users.add(new UserDTO(3L, 3));
  8. send(users);
  9. });
  10. }
  11. // 第 1 处
  12. private void send(List<UserDTO> users) {
  13. for (UserDTO userDto : users) {
  14. doSend(userDto);
  15. }
  16. }
  17. private static final Integer SOME_TYPE = 2;
  18. private void doSend(UserDTO userDTO) {
  19. String target = "default";
  20. // 第 2 处
  21. if (!userDTO.getType().equals(SOME_TYPE)) {
  22. target = getTarget(userDTO.getType());
  23. }
  24. System.out.println(String.format("userNo:%s, 发送到%s成功", userDTO, target));
  25. }
  26. private String getTarget(Integer type) {
  27. return type + "号基地";
  28. }

在第 1 处,如果集合为

  1. null


则会抛空指针;
在第 2 处,如果

  1. type


属性为

  1. null


则会抛空指针异常,导致后续都发送失败。
大家看这个例子觉得很简单,看到输入的参数有

  1. null


本能地就会考虑空指针问题,但是自己写代码时你并不知道上游是否会有

  1. null


。

**


实际开发中有些同学会有一些非常 “个性” 的写法。
为了避免空指针或避免检查到 null 参数抛异常,直接返回一个空参构造函数创建的对象。
类似下面的做法:

  1. /**
  2. * 根据订单编号查询订单
  3. *
  4. * @param orderNo 订单编号
  5. * @return 订单
  6. */
  7. public Order getByOrderNo(String orderNo) {
  8. if (StringUtils.isEmpty(orderNo)) {
  9. return new Order();
  10. }
  11. // 查询order
  12. return doGetByOrderNo(orderNo);
  13. }

由于常见的单个数据的查询接口,参数检查不符时会抛异常或者返回

  1. null


。 极少有上述的写法,因此调用方的惯例是判断结果不为

  1. null


就使用其中的属性。
这个哥们这么写之后,上层判断返回值不为

  1. null


, 上层就放心大胆得调用实例函数,导致线上报空指针,就造成了线上 BUG。

**


假如有一个订单更新的 RPC 接口,该接口有一个

  1. OrderUpdateParam


参数,之前有两个属性一个是

  1. id


一个是

  1. name


。在某个需求时,新增了一个 extra 属性,且该字段一定不能为

  1. null


。
采用 lombok 的

  1. @NonNull


注解来避免空指针:

  1. import lombok.Data;
  2. import lombok.NonNull;
  3. import java.io.Serializable;
  4. @Data
  5. public class OrderUpdateParam implements Serializable {
  6. private static final long serialVersionUID = 3240762365557530541L;
  7. private Long id;
  8. private String name;
  9. // 其它属性
  10. // 新增的属性
  11. @NonNull
  12. private String extra;
  13. }

上线后导致没有使用最新 jar 包的服务对该接口的 RPC 调用报错。
我们来分析一下原因,在 IDEA 的 target - classes 目录下找到 DEMO 编译后的 class 文件,IDEA 会自动帮我们反编译:

  1. public class OrderUpdateParam implements Serializable {
  2. private static final long serialVersionUID = 3240762365557530541L;
  3. private Long id;
  4. private String name;
  5. @NonNull
  6. private String extra;
  7. public OrderUpdateParam(@NonNull final String extra) {
  8. if (extra == null) {
  9. throw new NullPointerException("extra is marked non-null but is null");
  10. } else {
  11. this.extra = extra;
  12. }
  13. }
  14. @NonNull
  15. public String getExtra() {
  16. return this.extra;
  17. }
  18. public void setExtra(@NonNull final String extra) {
  19. if (extra == null) {
  20. throw new NullPointerException("extra is marked non-null but is null");
  21. } else {
  22. this.extra = extra;
  23. }
  24. }
  25. // 其他代码
  26. }

我们还可以使用反编译工具:JD-GUI 对编译后的 class 文件进行反编译,查看源码。
由于调用方调用的是不含

  1. extra


属性的 jar 包,并且序列化编号是一致的,反序列化时会抛出 NPE。

  1. Caused by: java.lang.NullPointerException: extra
  2. at com.xxx.OrderUpdateParam.<init>(OrderUpdateParam.java:21)

RPC 参数新增 lombok 的

  1. @NonNull


注解时,要考虑调用方是否及时更新 jar 包,避免出现空指针。

**


前面章节讲到了对象转换,如果我们下面的

  1. GoodCreateDTO


是我们自己服务的对象, 而

  1. GoodCreateParam


是我们调用服务的参数对象。

  1. @Data
  2. public class GoodCreateDTO {
  3. private String title;
  4. private Long price;
  5. private Long count;
  6. }
  7. @Data
  8. public class GoodCreateParam implements Serializable {
  9. private static final long serialVersionUID = -560222124628416274L;
  10. private String title;
  11. private long price;
  12. private long count;
  13. }

其中

  1. GoodCreateDTO


的

  1. count


属性在我们系统中是非必传参数,本系统可能为

  1. null


。
如果我们没有拉取源码的习惯,直接通过前面的转换工具类去转换。
我们潜意识会认为外部接口的对象类型也都是包装类型,这时候很容易因为转换出现 NPE 而导致线上 BUG。

  1. public class GoodCreateConverter {
  2. public static GoodCreateParam convertToParam(GoodCreateDTO goodCreateDTO) {
  3. if (goodCreateDTO == null) {
  4. return null;
  5. }
  6. GoodCreateParam goodCreateParam = new GoodCreateParam();
  7. goodCreateParam.setTitle(goodCreateDTO.getTitle());
  8. goodCreateParam.setPrice(goodCreateDTO.getPrice());
  9. goodCreateParam.setCount(goodCreateDTO.getCount());
  10. return goodCreateParam;
  11. }
  12. }

当转换器执行到

  1. goodCreateParam.setCount(goodCreateDTO.getCount());


会自动拆箱会报空指针。
当

  1. GoodCreateDTO


的

  1. count


属性为

  1. null


时,自动拆箱将报空指针。
再看一个花样踩坑的例子:
我们作为使用方调用如下的二方服务接口:

  1. public Boolean someRemoteCall();

然后自以为对方肯定会返回

  1. TRUE


或

  1. FALSE


,然后直接拿来作为判断条件或者转为基本类型,如果返回的是

  1. null


,则会报空指针异常:

  1. if (someRemoteCall()) {
  2. // 业务代码
  3. }

大家看示例的时候可能认为这种情况很简单,自己开发的时候肯定会注意,但是往往事实并非如此。
希望大家可以掌握常见的可能发生空指针场景,在开发是注意预防。

**


大家再看下面这个经典的例子。
因为某些批量查询的二方接口在数据较大时容易超时,因此可以分为小批次调用。
下面封装一个将

  1. List


数据拆分成每

  1. size


个一批数据,去调用

  1. function


RPC 接口,然后将结果合并。

  1. public static <T, V> List<V> partitionCallList(List<T> dataList, int size, Function<List<T>, List<V>> function) {
  2. if (CollectionUtils.isEmpty(dataList)) {
  3. return new ArrayList<>(0);
  4. }
  5. Preconditions.checkArgument(size > 0, "size 必须大于0");
  6. return Lists.partition(dataList, size)
  7. .stream()
  8. .map(function)
  9. .reduce(new ArrayList<>(),
  10. (resultList1, resultList2) -> {
  11. resultList1.addAll(resultList2);
  12. return resultList1;
  13. });
  14. }

看着挺对,没啥问题,其实则不然。
设想一下,如果某一个批次请求无数据,不是返回空集合而是 null,会怎样?
很不幸,又一个空指针异常向你飞来 …
此时要根据具体业务场景来判断如何处理这里可能产生的空指针异常。
如果在某个场景中,返回值为 null 是一定不允许的行为,可以在 function 函数中对结果进行检查,如果结果为 null,可抛异常。
如果是允许的,在调用 map 后,可以过滤 null :

  1. // 省略前面代码
  2. .map(function)
  3. .filter(Objects::nonNull)
  4. // 省略后续代码


**


  1. NPE


造成的线上 BUG 还有很多种形式,如何预防空指针很重要。
下面将介绍几种预防 NPE 的一些常见方法:

08 空指针引发的血案 - 图4 **

**


如果参数不符合要求直接返回空集合,底层的函数也使用一致的方式:

  1. public List<Order> getByOrderName(String name) {
  2. if (StringUtils.isNotEmpty(name)) {
  3. return doGetByOrderName(name);
  4. }
  5. return Collections.emptyList();
  6. }


**


  1. Optional


是 Java 8 引入的特性,返回一个

  1. Optional


则明确告诉使用者结果可能为空:

  1. public Optional<Order> getByOrderId(Long orderId) {
  2. return Optional.ofNullable(doGetByOrderId(orderId));
  3. }

如果大家感兴趣可以进入

  1. Optional


的源码,结合前面介绍的

  1. codota


工具进行深入学习,也可以结合《Java 8 实战》的相关章节进行学习。

**


该设计模式为了解决 NPE 产生原因的第 1 条 “调用

  1. null


对象的实例方法”。
在编写业务代码时为了避免

  1. NPE


经常需要先判空再执行实例方法:

  1. public void doSomeOperation(Operation operation) {
  2. int a = 5;
  3. int b = 6;
  4. if (operation != null) {
  5. operation.execute(a, b);
  6. }
  7. }

《设计模式之禅》(第二版)554 页在拓展篇讲述了 “空对象模式”。
可以构造一个

  1. NullXXX


类拓展自某个接口, 这样这个接口需要为

  1. null


时,直接返回该对象即可:

  1. public class NullOperation implements Operation {
  2. @Override
  3. public void execute(int a, int b) {
  4. // do nothing
  5. }
  6. }

这样上面的判空操作就不再有必要, 因为我们在需要出现

  1. null


的地方都统一返回

  1. NullOperation


,而且对应的对象方法都是有的:

  1. public void doSomeOperation(Operation operation) {
  2. int a = 5;
  3. int b = 6;
  4. operation.execute(a, b);
  5. }


**


讲完了接口的编写者该怎么做,我们讲讲接口的使用者该如何避免

  1. NPE


。

**


正如《代码简洁之道》第 7.8 节 “别传 null 值” 中所要表达的意义:
可以进行参数检查,对不满足的条件抛出异常。

直接在使用前对不能为

  1. null


的和不满足业务要求的条件进行检查,是一种最简单最常见的做法。
通过防御性参数检测,可以极大降低出错的概率,提高程序的健壮性:

  1. @Override
  2. public void updateOrder(OrderUpdateParam orderUpdateParam) {
  3. checkUpdateParam(orderUpdateParam);
  4. doUpdate(orderUpdateParam);
  5. }
  6. private void checkUpdateParam(OrderUpdateParam orderUpdateParam) {
  7. if (orderUpdateParam == null) {
  8. throw new IllegalArgumentException("参数不能为空");
  9. }
  10. Long id = orderUpdateParam.getId();
  11. String name = orderUpdateParam.getName();
  12. if (id == null) {
  13. throw new IllegalArgumentException("id不能为空");
  14. }
  15. if (name == null) {
  16. throw new IllegalArgumentException("name不能为空");
  17. }
  18. }

JDK 和各种开源框架中可以找到很多这种模式,

  1. java.util.concurrent.ThreadPoolExecutor#execute


就是采用这种模式。

  1. public void execute(Runnable command) {
  2. if (command == null)
  3. throw new NullPointerException();
  4. // 其他代码
  5. }

以及

  1. org.springframework.context.support.AbstractApplicationContext#assertBeanFactoryActive
  1. protected void assertBeanFactoryActive() {
  2. if (!this.active.get()) {
  3. if (this.closed.get()) {
  4. throw new IllegalStateException(getDisplayName() + " has been closed already");
  5. }
  6. else {
  7. throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
  8. }
  9. }
  10. }


**


可以使用 Java 7 引入的 Objects 类,来简化判空抛出空指针的代码。
使用方法如下:

  1. private void checkUpdateParam2(OrderUpdateParam orderUpdateParam) {
  2. Objects.requireNonNull(orderUpdateParam);
  3. Objects.requireNonNull(orderUpdateParam.getId());
  4. Objects.requireNonNull(orderUpdateParam.getName());
  5. }

原理很简单,我们看下源码;

  1. public static <T> T requireNonNull(T obj) {
  2. if (obj == null)
  3. throw new NullPointerException();
  4. return obj;
  5. }


**


我们可以使用 commons-lang3 或者 commons-collections4 等常用的工具类辅助我们判空。

**


  1. public void doSomething(String param) {
  2. if (StringUtils.isNotEmpty(param)) {
  3. // 使用param参数
  4. }
  5. }


**


  1. public static void doSomething(Object param) {
  2. Validate.notNull(param,"param must not null");
  3. }
  4. public static void doSomething2(List<String> parms) {
  5. Validate.notEmpty(parms);
  6. }

该校验工具类支持多种类型的校验,支持自定义提示文本等。
前面已经介绍了读源码是最好的学习方式之一,这里我们看下底层的源码:

  1. public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) {
  2. if (collection == null) {
  3. throw new NullPointerException(String.format(message, values));
  4. }
  5. if (collection.isEmpty()) {
  6. throw new IllegalArgumentException(String.format(message, values));
  7. }
  8. return collection;
  9. }

该如果集合对象为 null 则会抛空

  1. NullPointerException


如果集合为空则抛出

  1. IllegalArgumentException


。
通过源码我们还可以了解到更多的校验函数。
4.2.4 使用集合工具类:

  1. org.apache.commons.collections4.CollectionUtils


  1. public void doSomething(List<String> params) {
  2. if (CollectionUtils.isNotEmpty(params)) {
  3. // 使用params
  4. }
  5. }


**


可以使用 guava 包的

  1. com.google.common.base.Preconditions


前置条件检测类。
同样看源码,源码给出了一个范例。原始代码如下:

  1. public static double sqrt(double value) {
  2. if (value < 0) {
  3. throw new IllegalArgumentException("input is negative: " + value);
  4. }
  5. // calculate square root
  6. }

使用

  1. Preconditions


后,代码可以简化为:

  1. public static double sqrt(double value) {
  2. checkArgument(value >= 0, "input is negative: %s", value);
  3. // calculate square root
  4. }

Spring 源码里很多地方可以找到类似的用法,下面是其中一个例子:

  1. org.springframework.context.annotation.AnnotationConfigApplicationContext#register
  1. public void register(Class<?>... annotatedClasses) {
  2. Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
  3. this.reader.register(annotatedClasses);
  4. }
  1. org.springframework.util.Assert#notEmpty(java.lang.Object[], java.lang.String)
  1. public static void notEmpty(Object[] array, String message) {
  2. if (ObjectUtils.isEmpty(array)) {
  3. throw new IllegalArgumentException(message);
  4. }
  5. }

虽然使用的具体工具类不一样,核心的思想都是一致的。

**


4.2.6.1 使用 lombok 的

  1. @Nonnull

**


  1. public void doSomething5(@NonNull String param) {
  2. // 使用param
  3. proccess(param);
  4. }

查看编译后的代码:

  1. public void doSomething5(@NonNull String param) {
  2. if (param == null) {
  3. throw new NullPointerException("param is marked non-null but is null");
  4. } else {
  5. this.proccess(param);
  6. }
  7. }


**


maven 依赖如下:

  1. <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations -->
  2. <dependency>
  3. <groupId>org.jetbrains</groupId>
  4. <artifactId>annotations</artifactId>
  5. <version>17.0.0</version>
  6. </dependency>

@NotNull 在参数上的用法和上面的例子非常相似。

  1. public static void doSomething(@NotNull String param) {
  2. // 使用param
  3. proccess(param);
  4. }

我们可以去该注解的源码

  1. org.jetbrains.annotations.NotNull#exception


里查看更多细节,大家也可以使用 IDEA 插件或者前面介绍的 JD-GUI 来查看编译后的 class 文件,去了解 @NotNull 注解的作用。

**


本节主要讲述空指针的含义,空指针常见的中枪姿势,以及如何避免空指针异常。下一节将为你揭秘 当 switch 遇到空指针,又会发生什么奇妙的事情。

**


  1. 阿里巴巴与 Java 社区开发者.《 Java 开发手册 1.5.0:华山版》.2019:7,25 ↩︎
  2. James Gosling, Bill Joy, Guy Steele, Gilad Bracha, Alex Buckley.《Java Language Specification: Java SE 8 Edition》. 2015 ↩︎


07 过期类、属性、接口的正确处理姿势
09 当switch遇到空指针

精选留言 3
欢迎在这里发表留言,作者筛选后可公开显示


lombok 的 @NonNull,下次用一下
1
回复
2020-01-22


NPE无处不在一不小心就踩坑
1
回复
2020-01-15

回复慕标3246374

掌握应对空指针的技巧,可以少趟不少坑
回复
2020-01-17 00:54:41


非常实用!代码又能精进不少!
2
回复
2019-12-17

回复Seed2009

多了解一些新方法才能多一些选择,学以致用才是学习的目的