Java中替换对象属性值易出现错误

Posted web小菜鸟ing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中替换对象属性值易出现错误相关的知识,希望对你有一定的参考价值。

在项目中,需要对某个对象的某个值进行判断,并替换成别的值,一开始代码如下所示

if(tranIO.getDevice().equals("W"))
        tranIO.setDevice("终端窗口");
else if(tranIO.getDevice().equals("P"))
	tranIO.setDevice("打印机");
else if(tranIO.getDevice().equals("M"))
	tranIO.setDevice("磁条读写器");
else if(tranIO.getDevice()==null)
        tranIO.setDevice("");

 这里会造成一个 不容易发现的
错误就是 

当传进来的tranIO对象的device值为null时,系统会报错

原因在于,如果先按照这样的顺序执行

tranIO.getDevice().equals("W")
这段代码执行顺序就变成了

tranIO.getDevice()
然后再执行.equals("W")

 其实就是相当于执行 

null.equals("W")
这样当然会报错了


所以,修改成以下的方式就能够成功

if(tranIO.getDevice()==null)
	tranIO.setDevice("");
else if(tranIO.getDevice().equals("W"))
	tranIO.setDevice("终端窗口");
else if(tranIO.getDevice().equals("P"))
	tranIO.setDevice("打印机");
else if(tranIO.getDevice().equals("M"))
	tranIO.setDevice("磁条读写器");

先执行判断null,如果为null,赋值,并结束下面判断,即可

以上是关于Java中替换对象属性值易出现错误的主要内容,如果未能解决你的问题,请参考以下文章