我有一段看起来像这样的代码:
private void methodA(String a String b){
Employee e1=null;
foobar(e1,b); //line 1
//do something
if(e1!=null){ //line 2
//flow1
}else{
//flow2
}
}
private void foobar(Employee e, String a){
e= new Employee();
//do stuff
}
当我为此类运行findBugs时,它在第1行显示两个警告-
Load of known null value
The variable referenced at this point is known to be null due to an earlier check against null. Although this is valid, it might be a mistake (perhaps you intended to refer to a different variable, or perhaps the earlier check to see if the variable is null should have been a check to see if it was nonnull).
并在第2行:
Redundant nullcheck of value known to be null
This method contains a redundant check of a known null value against the constant null.
为了避免这些警告,我改为执行以下操作:
private void methodA(String a String b){
Employee e1 = foobar(b); //line 1
//do something
if(e1!=null){ //line 2
//flow1
}else{
//flow2
}
}
private Employee foobar(String a){
if("some_value".equals(a)){
Employee e= new Employee();
//do stuff
return e;
}
return null;
}
这样做可以从findbugs中删除警告,但是我的问题是此更改绝对必要,还是第一种方法会产生什么影响?
答案 0 :(得分:0)
Employee e1=null;
foobar(e1,b);
这是不正确的,因为foobar()
获得null
,并且在它之后不能引用e1。因此,if(e1!=null)
总是 false 。
Employee e1=null;
...
private void foobar(Employee e, String a){
e= new Employee();
//do stuff
}
e
引用了新对象,但这是方法的局部变量。