[英]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()
即使当test
是null
。
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.