奇数NullPointerException [英] Odd NullPointerException
问题描述
我的NPE中的Stacktrace开头为:
Stacktrace from my NPE starts with:
Caused by: java.lang.NullPointerException
at pl.yourvision.crm.web.servlets.listExport.ProductListExport.writeCells(ProductListExport.java:141)
此文件中的行号141为:
Line number 141 in this file is:
Double availablePieces = store != null ? store.getAvailablePieces() : 0.0;
其中store不为null且store.getAvailablePieces()为null的地方.我不明白为什么我会在这里例外.
Where store is not null and store.getAvailablePieces() is null. I do not understand why I get exception in here.
有什么想法吗?
推荐答案
我99%确信这是由于条件运算符的行为引起的.我相信您的代码等同于:
I'm 99% sure this is because of the behaviour of the conditional operator. I believe your code is equivalent to:
double tmp = store != null ? store.getAvailablePieces() : 0.0;
Double availablePieces = tmp;
换句话说,它会将 store.getAvailablePieces()
的结果装箱到 double
,然后装箱回到 Double
.如果 store.getAvailablePieces()
返回 null
,则确实会导致 NullPointerException
.
In other words, it's unboxing the result of store.getAvailablePieces()
to a double
, then boxing back to Double
. If store.getAvailablePieces()
returns null
, that will indeed cause a NullPointerException
.
解决方法是使第三个操作数也成为 Double
:
The fix is to make the third operand Double
as well:
Double availablePieces = store != null ? store.getAvailablePieces()
: Double.valueOf(0.0);
现在将没有装箱或拆箱,因此 store.getAvailablePieces()
返回 null
很好.然后,您可能想使用 0.0
代替,但这是另一回事.如果要这样做,可以更改为:
Now there won't be any boxing or unboxing, so it's fine for store.getAvailablePieces()
to return null
. You may want to then use 0.0
instead, but that's a different matter. If you're going to do that, you can change to:
Double tmp = store != null ? store.getAvailablePieces() : null:
double availablePieces = tmp == null ? 0.0 : tmp;
这篇关于奇数NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!