发布时间:2025-12-10 23:23:11 浏览次数:2
一般空指针的原因就是:当前正在使用的变量没有对应的值
也就是说:当前正在使用的变量没有引用指向对应的值/对象
也可以这样说:Null Pointer就相当于Null Reference
如下面的代码都会报空指针异常:
publicclassMain{publicstaticvoidmain(String[]args){Stringstr1=null;System.out.println(str1.toLowerCase());//NullPointerException}}publicclassMain{Stringstr2;//默认值为nullpublicstaticvoidmain(String[]args){Mainma=newMain();System.out.println(ma.str2.toLowerCase());//NullPointerException}}因为成员变量str2和局部变量str1都是默认为null,所以都没有具体的指向某个值/对象定位NullPointerException
如果产生了NullPointerException,例如,调用a.b.c.x()时产生了NullPointerException,原因可能是:
a是null;
a.b是null;
a.b.c是null;
确定到底是哪个对象是null以前只能打印这样的日志:
System.out.println(a);
System.out.println(a.b);
System.out.println(a.b.c);
如下面的代码:
publicclasstest20210629{publicstaticvoidmain(String[]args){Personp=newPerson();System.out.println(p.address.city);//输出:nullSystem.out.println(p.name[0]);//输出:nullSystem.out.println(p.address.city.toLowerCase());//空指针异常System.out.println(p.name[0].toLowerCase());//空指针异常}}classPerson{String[]name=newString[2];Addressaddress=newAddress();}classAddress{Stringcity;Stringstreet;Stringzipcode;}总结:
空指针发生的原因:一个变量A没有值(或没有指向对应的对象),然后直接使用A的方法,或者将A当成参数传给其他对象/方法使用,就会报空指针异常!
第一步,先看一下异常是怎么产生的,在输入一个这样的地址:http://localhost:8083/***/***/***/***?productId=564564564573534,在控制台就会如图所报错
第二步,要解决这样的空指针错误,就先要找到出错误的JAVA代码,点击就可以,如图:
第三步,定位到java代码后,在debug启动项目,并添加断点,怎么启动
第四步,继续第一步的地址,在debug的模式下可以看到此字段的值是Null, 如图:
第五步,输入正确的productId,如正确的链接是:http://localhost:8083/***/***/***/***?productId=47681438955545,如图,debug模式下此字段就不是null,如图:
第六步,如果没有其他错误的话,此时页面也应该打开了
读到这里,这篇“Java NullPointerException异常的原因是什么及怎么解决”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注本站行业资讯频道。