空指针异常添加空检查

Null Pointer Exception adding null check

在这一行解决空指针异常的简单且最好的方法:

oS = ((SyIntBVO)syIntBVOList.get(0)).getSource().trim();  

getSource 变量异常。如何添加空检查?

String oS = ((SyIntBVO)syIntBVOList.get(0)).getSource();

if(os != null) {
    os = oS.trim(); // we're good
} else {
    // deal with null
}

或者,如果 get(0) returns 为空,这将起作用:

SyIntBVO syIntBvo = ((SyIntBVO)syIntBVOList.get(0));

if(syIntBvo != null) {
    String os = SyIntBvo.getSource().trim(); // we're good
} else {
    // deal with null
}

为了决定您需要哪一个,我们需要更多详细信息,例如堆栈跟踪。

根据您 "defensive" 您需要的代码,从技术上讲,您 可能 需要检查 null 任何可能 可能null。在极端情况下,这是您取消引用的任何对象。例如...

syIntBVOList可以null吗?然后你需要在取消引用之前检查它:

if (syIntBVOList == null) {
    return;
}
SomeType variable = syIntBVOList.get(0);

variable可以null吗?它的铸造版本可以是null吗?

SyIntBVO anotherVariable = ((SyIntBVO)variable);
if (anotherVariable == null) {
    return;
}

可以getSource()returnnull吗?相同的模式。等等...

这真的取决于您的代码可以或不可以 null。如果一个对象的这些实例中的任何一个,无论是存储在变量中还是直接内联引用,都可以是 null 那么您需要在取消引用之前检查该 null 引用。

(注意:对于 应该 return 有时 return null 的实例,它通常被认为是一种反模式。正是出于这个原因,因为它需要消耗代码才能具有这种防御性。)