今天遇到的問題,也是寫代碼的習慣問題,邏輯沒有問題,但不規范,也不安全,
容易出現漏洞。
先將代碼貼出:
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);
通過一個三元運算,就可以輕松搞定,實在是高,特此進行記錄。