0%

Java 三元表达式空指针异常

场景

  • JDK 8/21
  • 业务使用三元表达式,获取结果抛出空指针
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
Integer source = 1;
Integer result = Objects.nonNull(source) ? getTarget() : 2;
System.out.println(result);
}

private static Integer getTarget() {
return null;
}

异常

1
2
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "com.test.service.NullPointService.getTarget()" is null
at com.record.service.NullPointService.main(NullPointService.java:32)

原因

处理

  • 显示判定

    1
    2
    3
    4
    5
    if (Objects.nonNull(source)) {
    if (Objects.isNull(target)) {
    log.error("target is null");
    }
    }
  • 指定类型, 避免触发分支预测时的拆装箱情况

    1
    2
    3
    Integer result = Objects.nonNull(source) ? Optional.ofNullable(target).orElse(null) : Integer.valueOf(2);
    log.info("source:{}, target:{} , result:{}", source, target, result);

代码记录

Code: https://github.com/swzxsyh/Case
Rivision Num: 9e5a514b6f9e57ed18c0989c9f05e22f3bb7b59a