Bigdecimal 空值验证的三元运算符

Ternary operator for Bigdecimal null validation

为什么我在这段代码中出现空指针异常?

    BigDecimal test = null;
    String data = "";
    try {
    System.out.println(test==null?"":test.toString());
    data = test==null?"":test.toString();
    System.out.println(data);
    data = data +  " " + test==null?"":test.toString(); // catching null pointer in this line
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

它将表达式计算为:

data = (data +  " " + test==null)?"":test.toString();

所以,由于 data + " " + test 不是 null,即使 testnull,它也会尝试调用 test.toString()

改变

data = data +  " " + test==null?"":test.toString();

data = data +  " " + (test==null?"":test.toString());

从 Java 8 开始,还有另一种方法来处理潜在的 null 引用:Optional

为了防止在将 BigDecimal 转换为 String 时出现 NPE,您可以像这样使用 Optional

String data = Optional.ofNullable(test).map(BigDecimal::toString).orElse("");

这样你就不需要多次检查 test 是否是 null。将 test 包裹在 Optional 中后,您可以努力确保安全,只有在 test 未引用 null 时才会执行任何转换 (map) .