Java中的字符串和空指针
下面的代码让我很生气:
private String blahBlah(){
return null;
}
@Test
public void myTest(){
System.out.println(blahBlah()); //Good, output "null"
Object obj = blahBlah();
System.out.println(obj.toString()) //Good as above
//System.out.println(blahBlah().toString()); //Bad, NullPointerException
//System.out.println(((Object)blahBlah()).toString()); //Bad as above
}
任何人都可以解释上述行为吗?
更新:
上面的代码不是事实。我实际经历的是,我收到了 NullPointerException 并且我回溯到 toString() 的调用,并且我尝试了不同的解决方法,包括语句内转换,但它不起作用。但是在我使用单独的强制转换之后,我不小心删除了 toString() 调用,因此它可以工作。
The following code makes me mad:
private String blahBlah(){
return null;
}
@Test
public void myTest(){
System.out.println(blahBlah()); //Good, output "null"
Object obj = blahBlah();
System.out.println(obj.toString()) //Good as above
//System.out.println(blahBlah().toString()); //Bad, NullPointerException
//System.out.println(((Object)blahBlah()).toString()); //Bad as above
}
Can anyone explain the above behavior?
UPDATE:
The above code is NOT the truth. What I actually experienced is that I received NullPointerException and I track back to the call of toString(), and I tried different workarounds including in-statement casting but it does'nt work. But after I use seperated cast I accidentally removed the toString()
call so it WORKED.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简单的。
您可以打印
null
;您只是无法取消引用null
值。Easy.
You can print a
null
; you just can't de-reference anull
value.因为您返回的是指向 null 的字符串,而不是指向值为 null 的字符串。尝试将 return null 更改为 return ""。
Because you are returning a string pointing at null instead of pointing at a string with the value null. Try changing return null to return "".
您可以使用
String.valueOf(Object)
从对象获取toString
输出,如果传入的值为,则使用
。null
空http://docs .oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)
You can use
String.valueOf(Object)
to get thetoString
output from an object, ornull
if the value passed in isnull
.http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)