开发者

Why does this throw NullPointerException?

开发者 https://www.devze.com 2022-12-29 06:34 出处:网络
e.getCategory() != null ? e.getCategory().getName() : \"\"; This throws a 开发者_如何学GoNullPointerException and I do not understand why. Can anyone explain?Explanation:
e.getCategory() != null ? e.getCategory().getName() : "";

This throws a 开发者_如何学GoNullPointerException and I do not understand why. Can anyone explain?


Explanation:

According to Java's precedence rules, your code was being parsed like this:

(("\"category\":" + "\"" + e.getCategory()) != null) ? e.getCategory().getName() : ""

with the entire concatenation (("..." + e.getCategory())!= null) as the condition.

Since "..." + e.getCategory() is never null, the code didn't work.


e is null.


Is e null?

Perhaps you should try this:

(e != null) ?
    (e.getCategory() != null) ?
        e.getCategory().getName() : 
        ""
    : ""

Or rather, a simplified form:

(e != null && e.getCategory() != null) ?
    e.getCategory().getName() : 
    ""


Solution found....

CORRECT

bufo.append("\"category\":" + "\"" + ((e.getCategory() != null) ? e.getCategory().getName() : "") + "\",");

PROBLEM

bufo.append("\"category\":" + "\"" + e.getCategory()!=null?e.getCategory().getName():"" + "\",");
0

精彩评论

暂无评论...
验证码 换一张
取 消