我正在使用 Sonarqube 分析我的 Java 代码,我收到了消息的几个问题:
String literal expressions should be on the left side of an equals comparison
这很容易用字符串解决,翻转顺序以避免可能的NullPointerException
//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.getIntegerAttribute
为 null
的情况。
请注意,这不会产生任何开销:声明 Integer value = 1
会编译为 Integer value = Integer.valueOf(1)
。另请注意,由于此值 (1) 已缓存,因此它实际上不会创建新的 Integer
对象。
关于java - Sonarqube 对非字符串类型说 "String literal expressions should be on the left side of an equals comparison",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312405/