简体   繁体   English

用于Bigdecimal null验证的三元运算符

[英]Ternary operator for Bigdecimal null validation

Why am I getting null pointer exception in this code? 为什么我在这段代码中得到空指针异常?

    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();
    }

It's evaluating the expressions as: 它将表达式评估为:

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

so, since data + " " + test is not null , it attempts to call test.toString() even when test is null . 所以,由于data + " " + test是不null ,则尝试调用test.toString()即使当testnull

Change 更改

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

to

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

Since Java 8 there is also an alternative way to deal with potential null references: Optional 从Java 8开始,还有另一种处理潜在null引用的方法: Optional

To prevent an NPE while converting a BigDecimal to a String you can use an Optional like that: 要在将BigDecimal转换为String时阻止NPE,您可以使用如下可Optional

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

This way you don't need to check test several times if it is null . 这样,如果它为null ,则不需要多次检查test Having test once wrapped in an Optional you could work on being safe, that any conversion ( map ) will be performed only if test is not referencing null . test一旦包含在Optional您就可以确保安全,只有在test不引用null才会执行任何转换( map )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM