Odd NullPointerException

前端 未结 1 1671
夕颜
夕颜 2021-01-05 15:37

Stacktrace from my NPE starts with:

Caused by: java.lang.NullPointerException
    at pl.yourvision.crm.web.servlets.listExport.ProductListExport.writeCells(P         


        
相关标签:
1条回答
  • 2021-01-05 16:18

    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;
    

    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.

    The fix is to make the third operand Double as well:

    Double availablePieces = store != null ? store.getAvailablePieces()
                                           : Double.valueOf(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;
    
    0 讨论(0)
提交回复
热议问题