为什么会抛出NullPointerException?

问题描述:

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

这会抛出一个NullPointerException,我不明白为什么。谁能解释一下?为什么会抛出NullPointerException?

+2

请发布您的NullPointerException的完整堆栈跟踪。它应该帮助确切地揭示问题发生的位置。 – 2010-05-04 13:24:39

+2

只是一个提示:在Java中,通常认为在大多数操作符的任一侧放置一个空格是很好的做法,如'!=','?'和':'。它使这样的代码更具可读性。 – Syntactic 2010-05-04 13:25:34

+1

感谢提示 – GorillaApe 2010-05-04 13:32:54

说明:

根据Java的优先规则,你的代码是被解析如下:

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

与整个级联(("..." + e.getCategory())!= null)作为条件。

由于"..." + e.getCategory()从不是null,代码无法正常工作。

enull

+0

它不是零! – GorillaApe 2010-05-04 13:24:00

+0

(e.getCategory()!= null)返回false或true,从不抛出异常 – GorillaApe 2010-05-04 13:24:29

+3

**然后在'getName()'里面有一个问题。** – SLaks 2010-05-04 13:24:55

e null?

也许你应该试试这个:

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

或者说,一个简单的形式:

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

如果语句存在,则有一个原因...'if(e!= null && e.getCategory()!= null && ...)...' – 2010-05-04 13:29:26

+0

但是三元表达式是funner ! :-) – amphetamachine 2010-05-04 15:17:06

发现的解决方案....

正确

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

问题

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

它似乎需要()出于某种原因 – GorillaApe 2010-05-04 13:33:50

+1

它需要()因为否则你测试字符串“category”:“null而不是测试实际引用,它是null。编译器假定你测试结果的字符串连接 – 2010-05-04 13:38:07

+1

这使得有时使用临时变量来简化表达式会更好,即使您知道运算符优先级规则很冷,下一个可能读到代码的可怜的懒汉也许不会...... – 2010-05-04 13:38:24