《手册》的第 7 页和 25 页有两段关于空指针的描述:html
【强制】Object 的 equals 方法容易抛空指针异常,应使用常量或肯定有值的对象来调用 equals。java
【推荐】防止 NPE,是程序员的基本修养,注意 NPE 产生的场景:git
- 返回类型为基本数据类型,return 包装数据类型的对象时,自动拆箱有可能产生 NPE。
反例:public int f () { return Integer 对象}, 若是为 null,自动解箱抛 NPE。程序员
- 数据库的查询结果可能为 null。
- 集合里的元素即便 isNotEmpty,取出的数据元素也可能为 null。
- 远程调用返回对象时,一概要求进行空指针判断,防止 NPE。
- 对于 Session 中获取的数据,建议进行 NPE 检查,避免空指针。
- 级联调用 obj.getA ().getB ().getC (); 一连串调用,易产生 NPE。
《手册》对空指针常见的缘由和基本的避免空指针异常的方式给了介绍,很是有参考价值。github
那么咱们思考如下几个问题:spring
NullPointerException
(简称为 NPE)?前面介绍过源码是学习的一个重要途径,咱们一块儿看看NullPointerException
的源码:数据库
/** * Thrown when an application attempts to use {@code null} in a * case where an object is required. These include: * <ul> * <li>Calling the instance method of a {@code null} object. * <li>Accessing or modifying the field of a {@code null} object. * <li>Taking the length of {@code null} as if it were an array. * <li>Accessing or modifying the slots of {@code null} as if it * were an array. * <li>Throwing {@code null} as if it were a {@code Throwable} * value. * </ul> * <p> * Applications should throw instances of this class to indicate * other illegal uses of the {@code null} object. * * {@code NullPointerException} objects may be constructed by the * virtual machine as if {@linkplain Throwable#Throwable(String, * Throwable, boolean, boolean) suppression were disabled and/or the * stack trace was not writable}. * * @author unascribed * @since JDK1.0 */ public class NullPointerException extends RuntimeException { private static final long serialVersionUID = 5162710183389028792L; /** * Constructs a {@code NullPointerException} with no detail message. */ public NullPointerException() { super(); } /** * Constructs a {@code NullPointerException} with the specified * detail message. * * @param s the detail message. */ public NullPointerException(String s) { super(s); } }
源码注释给出了很是详尽地解释:apache
空指针发生的缘由是应用须要一个对象时却传入了
null
,包含如下几种状况:设计模式
- 调用 null 对象的实例方法。
- 访问或者修改 null 对象的属性。
- 获取值为 null 的数组的长度。
- 访问或者修改值为 null 的二维数组的列时。
- 把 null 当作 Throwable 对象抛出时。
实际编写代码时,产生空指针的缘由都是这些状况或者这些状况的变种。数组
《手册》中的另一处描述
“集合里的元素即便 isNotEmpty,取出的数据元素也可能为
null
。”
和第 4 条很是相似。
如《手册》中的:
“级联调用 obj.getA ().getB ().getC (); 一连串调用,易产生 NPE。”
和第 1 条很相似,由于每一层均可能获得null
。
当遇到《手册》中和源码注释中所描述的这些场景时,要注意预防空指针。
另外经过读源码注释咱们还获得了 “意外发现”,JVM 也可能会经过Throwable#Throwable(String, Throwable, boolean, boolean)
构造函数来构造NullPointerException
对象。
经过源码能够看到 NPE 继承自RuntimeException
咱们能够经过 IDEA 的 “Java Class Diagram” 来查看类的继承体系。
能够清晰地看到 NPE 继承自RuntimeException
,另外咱们选取NoSuchFieldException
和NoSuchFieldError
和NoClassDefFoundError
,能够看到Throwable
的子类型包括Error
和Exception
, 其中 NPE 又是Exception
的子类。
那么为何Exception
和Error
有什么区别?Excption
又分为哪些类型呢?
咱们能够分别去java.lang.Exception
和java.lang.Error
的源码注释中寻找答案。
经过Exception
的源码注释咱们了解到,Exception
分为两类一种是非受检异常(uncheked exceptions)即java.lang.RuntimeException
以及其子类;而受检异常(checked exceptions)的抛出须要再普通函数或构造方法上经过throws
声明。
经过java.lang.Error
的源码注释咱们了解到,Error
表明严重的问题,不该该被程序try-catch
。编译时异常检测时,Error
也被视为不可检异常(uncheked exceptions)。
你们能够在 IDEA 中分别查看Exception
和Error
的子类,了解本身开发中常遇到的异常都属于哪一个分类。
咱们还能够经过《JLS》第 11 章Exceptions对异常进行学习。
其中在异常的类型这里,讲到:
不可检异常( unchecked exception)包括运行时异常和 error 类。可检异常(checked exception)不属于不可检异常的全部异常都是可检异常。除 RuntimeException 和其子类,以及 Error 类以及其子类外的其余 Throwable 的子类。
还有更多关于异常的详细描述,,包括异常的缘由、异步异常、异常的编译时检查等,你们能够本身进一步学习。
@Test public void test() { Assertions.assertThrows(NullPointerException.class, () -> { List<UserDTO> users = new ArrayList<>(); users.add(new UserDTO(1L, 3)); users.add(new UserDTO(2L, null)); users.add(new UserDTO(3L, 3)); send(users); }); } // 第 1 处 private void send(List<UserDTO> users) { for (UserDTO userDto : users) { doSend(userDto); } } private static final Integer SOME_TYPE = 2; private void doSend(UserDTO userDTO) { String target = "default"; // 第 2 处 if (!userDTO.getType().equals(SOME_TYPE)) { target = getTarget(userDTO.getType()); } System.out.println(String.format("userNo:%s, 发送到%s成功", userDTO, target)); } private String getTarget(Integer type) { return type + "号基地"; }
在第 1 处,若是集合为null
则会抛空指针;
在第 2 处,若是type
属性为null
则会抛空指针异常,致使后续都发送失败。
你们看这个例子以为很简单,看到输入的参数有null
本能地就会考虑空指针问题,可是本身写代码时你并不知道上游是否会有null
。
实际开发中有些同窗会有一些很是 “个性” 的写法。
为了不空指针或避免检查到 null 参数抛异常,直接返回一个空参构造函数建立的对象。
相似下面的作法:
/** * 根据订单编号查询订单 * * @param orderNo 订单编号 * @return 订单 */ public Order getByOrderNo(String orderNo) { if (StringUtils.isEmpty(orderNo)) { return new Order(); } // 查询order return doGetByOrderNo(orderNo); }
因为常见的单个数据的查询接口,参数检查不符时会抛异常或者返回null
。 极少有上述的写法,所以调用方的惯例是判断结果不为null
就使用其中的属性。
这个哥们这么写以后,上层判断返回值不为null
, 上层就放心大胆得调用实例函数,致使线上报空指针,就形成了线上 BUG。
假若有一个订单更新的 RPC 接口,该接口有一个OrderUpdateParam
参数,以前有两个属性一个是id
一个是name
。在某个需求时,新增了一个 extra 属性,且该字段必定不能为null
。
采用 lombok 的@NonNull
注解来避免空指针:
import lombok.Data; import lombok.NonNull; import java.io.Serializable; @Data public class OrderUpdateParam implements Serializable { private static final long serialVersionUID = 3240762365557530541L; private Long id; private String name; // 其它属性 // 新增的属性 @NonNull private String extra; }
上线后致使没有使用最新 jar 包的服务对该接口的 RPC 调用报错。
咱们来分析一下缘由,在 IDEA 的 target - classes 目录下找到 DEMO 编译后的 class 文件,IDEA 会自动帮咱们反编译:
public class OrderUpdateParam implements Serializable { private static final long serialVersionUID = 3240762365557530541L; private Long id; private String name; @NonNull private String extra; public OrderUpdateParam(@NonNull final String extra) { if (extra == null) { throw new NullPointerException("extra is marked non-null but is null"); } else { this.extra = extra; } } @NonNull public String getExtra() { return this.extra; } public void setExtra(@NonNull final String extra) { if (extra == null) { throw new NullPointerException("extra is marked non-null but is null"); } else { this.extra = extra; } } // 其余代码 }
咱们还可使用反编译工具:JD-GUI对编译后的 class 文件进行反编译,查看源码。
因为调用方调用的是不含extra
属性的 jar 包,而且序列化编号是一致的,反序列化时会抛出 NPE。
Caused by: java.lang.NullPointerException: extra at com.xxx.OrderUpdateParam.<init>(OrderUpdateParam.java:21)
RPC 参数新增 lombok 的@NonNull
注解时,要考虑调用方是否及时更新 jar 包,避免出现空指针。
前面章节讲到了对象转换,若是咱们下面的GoodCreateDTO
是咱们本身服务的对象, 而GoodCreateParam
是咱们调用服务的参数对象。
@Data public class GoodCreateDTO { private String title; private Long price; private Long count; } @Data public class GoodCreateParam implements Serializable { private static final long serialVersionUID = -560222124628416274L; private String title; private long price; private long count; }
其中GoodCreateDTO
的count
属性在咱们系统中是非必传参数,本系统可能为null
。
若是咱们没有拉取源码的习惯,直接经过前面的转换工具类去转换。
咱们潜意识会认为外部接口的对象类型也都是包装类型,这时候很容易由于转换出现 NPE 而致使线上 BUG。
public class GoodCreateConverter { public static GoodCreateParam convertToParam(GoodCreateDTO goodCreateDTO) { if (goodCreateDTO == null) { return null; } GoodCreateParam goodCreateParam = new GoodCreateParam(); goodCreateParam.setTitle(goodCreateDTO.getTitle()); goodCreateParam.setPrice(goodCreateDTO.getPrice()); goodCreateParam.setCount(goodCreateDTO.getCount()); return goodCreateParam; } }
当转换器执行到goodCreateParam.setCount(goodCreateDTO.getCount());
会自动拆箱会报空指针。
当GoodCreateDTO
的count
属性为null
时,自动拆箱将报空指针。
再看一个花样踩坑的例子:
咱们做为使用方调用以下的二方服务接口:
public Boolean someRemoteCall();
而后自觉得对方确定会返回TRUE
或FALSE
,而后直接拿来做为判断条件或者转为基本类型,若是返回的是null
,则会报空指针异常:
if (someRemoteCall()) { // 业务代码 }
你们看示例的时候可能认为这种状况很简单,本身开发的时候确定会注意,可是每每事实并不是如此。
但愿你们能够掌握常见的可能发生空指针场景,在开发是注意预防。
你们再看下面这个经典的例子。
由于某些批量查询的二方接口在数据较大时容易超时,所以能够分为小批次调用。
下面封装一个将List
数据拆分红每size
个一批数据,去调用function
RPC 接口,而后将结果合并。
public static <T, V> List<V> partitionCallList(List<T> dataList, int size, Function<List<T>, List<V>> function) { if (CollectionUtils.isEmpty(dataList)) { return new ArrayList<>(0); } Preconditions.checkArgument(size > 0, "size 必须大于0"); return Lists.partition(dataList, size) .stream() .map(function) .reduce(new ArrayList<>(), (resultList1, resultList2) -> { resultList1.addAll(resultList2); return resultList1; }); }
看着挺对,没啥问题,其实则否则。
设想一下,若是某一个批次请求无数据,不是返回空集合而是 null,会怎样?
很不幸,又一个空指针异常向你飞来 …
此时要根据具体业务场景来判断如何处理这里可能产生的空指针异常。
若是在某个场景中,返回值为 null 是必定不容许的行为,能够在 function 函数中对结果进行检查,若是结果为 null,可抛异常。
若是是容许的,在调用 map 后,能够过滤 null :
// 省略前面代码 .map(function) .filter(Objects::nonNull) // 省略后续代码
NPE
形成的线上 BUG 还有不少种形式,如何预防空指针很重要。
下面将介绍几种预防 NPE 的一些常见方法:
若是参数不符合要求直接返回空集合,底层的函数也使用一致的方式:
public List<Order> getByOrderName(String name) { if (StringUtils.isNotEmpty(name)) { return doGetByOrderName(name); } return Collections.emptyList(); }
Optional
是 Java 8 引入的特性,返回一个Optional
则明确告诉使用者结果可能为空:
public Optional<Order> getByOrderId(Long orderId) { return Optional.ofNullable(doGetByOrderId(orderId)); }
若是你们感兴趣能够进入Optional
的源码,结合前面介绍的codota
工具进行深刻学习,也能够结合《Java 8 实战》的相关章节进行学习。
该设计模式为了解决 NPE 产生缘由的第 1 条 “调用null
对象的实例方法”。
在编写业务代码时为了不NPE
常常须要先判空再执行实例方法:
public void doSomeOperation(Operation operation) { int a = 5; int b = 6; if (operation != null) { operation.execute(a, b); } }
《设计模式之禅》(第二版)554 页在拓展篇讲述了 “空对象模式”。
能够构造一个NullXXX
类拓展自某个接口, 这样这个接口须要为null
时,直接返回该对象便可:
public class NullOperation implements Operation { @Override public void execute(int a, int b) { // do nothing } }
这样上面的判空操做就再也不有必要, 由于咱们在须要出现null
的地方都统一返回NullOperation
,并且对应的对象方法都是有的:
public void doSomeOperation(Operation operation) { int a = 5; int b = 6; operation.execute(a, b); }
讲完了接口的编写者该怎么作,咱们讲讲接口的使用者该如何避免NPE
。
正如《代码简洁之道》第 7.8 节 “别传 null 值” 中所要表达的意义:
能够进行参数检查,对不知足的条件抛出异常。
直接在使用前对不能为null
的和不知足业务要求的条件进行检查,是一种最简单最多见的作法。
经过防护性参数检测,能够极大下降出错的几率,提升程序的健壮性:
@Override public void updateOrder(OrderUpdateParam orderUpdateParam) { checkUpdateParam(orderUpdateParam); doUpdate(orderUpdateParam); } private void checkUpdateParam(OrderUpdateParam orderUpdateParam) { if (orderUpdateParam == null) { throw new IllegalArgumentException("参数不能为空"); } Long id = orderUpdateParam.getId(); String name = orderUpdateParam.getName(); if (id == null) { throw new IllegalArgumentException("id不能为空"); } if (name == null) { throw new IllegalArgumentException("name不能为空"); } }
JDK 和各类开源框架中能够找到不少这种模式,java.util.concurrent.ThreadPoolExecutor#execute
就是采用这种模式。
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); // 其余代码 }
以及org.springframework.context.support.AbstractApplicationContext#assertBeanFactoryActive
protected void assertBeanFactoryActive() { if (!this.active.get()) { if (this.closed.get()) { throw new IllegalStateException(getDisplayName() + " has been closed already"); } else { throw new IllegalStateException(getDisplayName() + " has not been refreshed yet"); } } }
可使用 Java 7 引入的 Objects 类,来简化判空抛出空指针的代码。
使用方法以下:
private void checkUpdateParam2(OrderUpdateParam orderUpdateParam) { Objects.requireNonNull(orderUpdateParam); Objects.requireNonNull(orderUpdateParam.getId()); Objects.requireNonNull(orderUpdateParam.getName()); }
原理很简单,咱们看下源码;
public static <T> T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }
咱们可使用 commons-lang3 或者 commons-collections4 等经常使用的工具类辅助咱们判空。
public void doSomething(String param) { if (StringUtils.isNotEmpty(param)) { // 使用param参数 } }
public static void doSomething(Object param) { Validate.notNull(param,"param must not null"); } public static void doSomething2(List<String> parms) { Validate.notEmpty(parms); }
该校验工具类支持多种类型的校验,支持自定义提示文本等。
前面已经介绍了读源码是最好的学习方式之一,这里咱们看下底层的源码:
public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) { if (collection == null) { throw new NullPointerException(String.format(message, values)); } if (collection.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return collection; }
该若是集合对象为 null 则会抛空NullPointerException
若是集合为空则抛出IllegalArgumentException
。
经过源码咱们还能够了解到更多的校验函数。
org.apache.commons.collections4.CollectionUtils
public void doSomething(List<String> params) { if (CollectionUtils.isNotEmpty(params)) { // 使用params } }
可使用 guava 包的com.google.common.base.Preconditions
前置条件检测类。
一样看源码,源码给出了一个范例。原始代码以下:
public static double sqrt(double value) { if (value < 0) { throw new IllegalArgumentException("input is negative: " + value); } // calculate square root }
使用Preconditions
后,代码能够简化为:
public static double sqrt(double value) { checkArgument(value >= 0, "input is negative: %s", value); // calculate square root }
Spring 源码里不少地方能够找到相似的用法,下面是其中一个例子:
org.springframework.context.annotation.AnnotationConfigApplicationContext#register
public void register(Class<?>... annotatedClasses) { Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); this.reader.register(annotatedClasses); }
org.springframework.util.Assert#notEmpty(java.lang.Object[], java.lang.String)
public static void notEmpty(Object[] array, String message) { if (ObjectUtils.isEmpty(array)) { throw new IllegalArgumentException(message); } }
虽然使用的具体工具类不同,核心的思想都是一致的。
@Nonnull
注解public void doSomething5(@NonNull String param) { // 使用param proccess(param); }
查看编译后的代码:
public void doSomething5(@NonNull String param) { if (param == null) { throw new NullPointerException("param is marked non-null but is null"); } else { this.proccess(param); } }
maven 依赖以下:
<!-- https://mvnrepository.com/artifact/org.jetbrains/annotations --> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>17.0.0</version> </dependency>
@NotNull 在参数上的用法和上面的例子很是类似。
public static void doSomething(@NotNull String param) { // 使用param proccess(param); }
咱们能够去该注解的源码org.jetbrains.annotations.NotNull#exception
里查看更多细节,你们也可使用 IDEA 插件或者前面介绍的 JD-GUI 来查看编译后的 class 文件,去了解 @NotNull 注解的做用。
本节主要讲述空指针的含义,空指针常见的中枪姿式,以及如何避免空指针异常。下一节将为你揭秘 当 switch 遇到空指针,又会发生什么奇妙的事情。