java - 为什么简单的获取一个空的字符串会报空指针错误?
高洛峰
高洛峰 2017-04-17 14:56:49
0
3
600
String s=forecast.getStatus();

就是这么简单的一行代码,forecast是我自己建的一个bean,public class Forecast 里面都是简单的set和get。
现在因为我没有进行set,所以这个Status应该是默认的null才对,获取null还会报空指针错误?

IDE的错误报告:Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.leu.littleweather.bean.Forecast.getStatus()' on a null object reference

神奇的是有时候它又不会报错,有时候会报错。。。真是日了狗了!

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
小葫芦

getStatus() on a null object reference means that forecast is null and you cannot call methods on null objects. So you need to check what causes forecast to be null sometimes and not null sometimes.

阿神

It means your forecast is empty. .

迷茫

If the object is empty, of course a null pointer is reported.

Just like if you don’t have a girlfriend, do you still expect to adjust your girlfriend’s API? If you want to adjust it, do you need to buy a girlfriend first?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!