当对象或对象属性为空时,如何安全给对象或对象属性添加默认值

今天遇到的问题,也是写代码的习惯问题,逻辑没有问题,但不规范,也不安全,

容易出现漏洞。

先将代码贴出:

 String isPrintLogo = vodInfoDto.getIsPrintLogo();
            if(!isPrintLogo.equalsIgnoreCase("0")){
               isPrintLogo="1";
                demandVideoInfo.setIsPrintLogo(isPrintLogo);
          }

代码原意为:判断对象属性,并给对象的该属性判断是否为预定的值,

如果不是,则进行设置默认值。

本能的想为对象的属性不为空,当对象的属性不为空时,代码则会正常运行。

但当对象为空或对象的属性为空是,则会产生空指针异常。

遇到了以为大神,请教他之后,他给出了两种方案,

一种是 :

String isPrintLogo = vodInfoDto.getIsPrintLogo();
            if(!"0".equalsIgnoreCase("isPrintLogo")){
               isPrintLogo="1";
                demandVideoInfo.setIsPrintLogo(isPrintLogo);
          }

将比较的属性值放入到equals后面中,也会规避异常出现。

另一种是:

        demandVideoInfo.setIsPrintLogo("null".equalsIgnoreCase(isPrintLogo)?"1":isPrintLogo);
通过一个三元运算,就可以轻松搞定,实在是高,特此进行记录。

原文地址:https://www.cnblogs.com/zjdxr-up/p/7524177.html