java.lang.NullPointerException
对一个 null 引用调用方法或访问字段时抛出,Java 最常见运行时异常。
现象
Exception in thread "main" java.lang.NullPointerException
at com.demo.UserService.getEmail(UserService.java:42)
at com.demo.Main.main(Main.java:12)原因
- 对象未初始化(声明但未 new)就使用。
- 方法返回了 null,调用方未判空直接链式访问(
user.getAddress().getCity())。 - 从 Map/集合/数据库查询取到 null 元素。
- 自动拆箱时包装类型为 null(
Integer → int)。
解决
// 1. 早判空(防御式)
if (user != null && user.getAddress() != null) {
String city = user.getAddress().getCity();
}
// 2. 用 Optional
Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.ifPresent(System.out::println);
// 3. 看堆栈定位到第 42 行,确认哪个变量为 null预防
- 方法尽量不返回 null,返回空集合/Optional。
- 开启 IDE/SpotBugs 的 @Nullable 检查。
- 用
Objects.requireNonNull()在入口校验参数。