开发者

Why does this throw NullPointerException?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜