Sonarqube 表示非字符串类型的"String literal expressions should be on the left side of an equals comparison"



我正在使用Sonarqube来分析我的Java代码,并且我收到了以下消息的几个问题:

字符串文字表达式应位于相等比较的左侧

这很容易用字符串来解决,可以翻转顺序以避免可能的NullPointerException s

//From this:
myString.equals("otherString");
//To this:
"otherString".equals(myString);

然而,我在使用非字符串类型时遇到了这些问题,例如在以下代码中:

if (myObject.getIntegerAttribute.equals(1)){ // <-Sonarqube shows the issue here
    // ...
}

既然我不能翻转"1",因为它是一个基元类型,并且没有equals()方法,我该如何解决这些问题?

您可以通过将int显式装箱为Integer:来解决此问题

if (Integer.valueOf(1).equals(myObject.getIntegerAttribute)) { // <-- explicit box
    // ...
}

这将通过返回false来正确处理myObject.getIntegerAttributenull的情况。

请注意,这不会产生任何开销:声明Integer value = 1编译为Integer value = Integer.valueOf(1)。还要注意,由于这个值(1)是缓存的,它实际上不会创建新的Integer对象。

Integer test = 1;
if ( test.equals(myObject.getIntegerAttribute())

应该有助于解决您的问题。再说一遍:存储一个局部变量真的值得吗?

if ( Integer.valueOf(1).equals(myObject.getIntegerAttribute())

这可能是一个进步。

由于你可以自己配置声纳规则,很难说哪一个最适合你的配置。

相关内容