[英]SonarQube Java 'NullPointerException might be thrown' in if statement
I get a kind of following error from solarQube = " NullPointerException might be thrown as 'a' is nullable here ". 我从solarQube中得到了一种以下错误=“ NullPointerException可能会因为'a'在此处为空而抛出 ”。 Below is simple code sample for the error.
下面是该错误的简单代码示例。
The class : 班级 :
class A {
int a1;
int a2;
public A () {
}
public int getA1() {
return a1;
}
public int getA2() {
return a2;
}
}
Then I have a method which use the class above as param : 然后我有一个使用上面的类作为param的方法:
public boolean testMethod(A a) {
if(a != null && a.getA1() != 1 || a.getA2() != 2) {
return true;
}
return false;
}
I got the error with a.getA2 != 2
highlighted by SonarQube. 我得到了
a.getA2 != 2
突出显示的a.getA2 a.getA2 != 2
错误。 I just cannot understand the problem with those statement. 我只是无法理解那些陈述的问题。 The description of the bug describes by the SonarQube did not makes me any clearer.
SonarQube所描述的错误的描述没有让我更清楚。 How can I fix it and can anyone please explain to me why it is an error ?
我该如何解决它?有人可以向我解释为什么这是一个错误吗?
Think to the operators precedence : &&
has higher priority than ||
考虑到运算符的优先级 :
&&
优先级高于||
. 。
Operators with higher precedence are evaluated before operators with relatively lower precedence. 具有较高优先级的运算符将在具有较低优先级的运算符之前进行评估。
So you have to understand this statement : 因此,您必须了解以下语句:
if(a != null && a.getA1() != 1 || a.getA2() != 2)
as whether it was written : 就像是写的一样:
// Evaluated together // Evaluated then
if( (a != null && a.getA1() != 1) || a.getA2() != 2)
So a.getA2() != 2
doesn't have a null
check. 因此
a.getA2() != 2
没有null
检查。
What you have to write to prevent NullPointerException
is grouped the evaluation of the two boolean expressions that need to. 为防止
NullPointerException
而必须编写的内容被分组为对两个布尔表达式的求值。
You can do it by surrounding them by parenthesis : 您可以通过用括号将它们括起来来实现:
if(a != null && (a.getA1() != 1 || a.getA2() != 2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.