当我们尝试将 Java 盒装基元与“==”而不是“.equals”进行比较时,我可以生成警告吗?

Can I generate warnings when we try to compare Java boxed primitives with "==" instead of ".equals"?

NPE 被描述为“十亿美元的错误”。我不得不相信紧随其后的可能是将盒装基元与“==”而不是 .equals(...) 进行比较。

当我们的代码库的一部分 returns 是 Long 而不是 long,例如:

class Car {
  Long speed;
}

Car carA, carB;
boolean res1 = carA.getSpeed() == carB.getSpeed(); // could fail if the speeds are equal because the wrappers are distinct.

boolean res2 = Objects.equals(carA.getSpeed(), carB.getSpeed()); // compares by value and works

这种东西在PR中很容易漏掉。有没有办法生成警告以捕捉这种情况?我们使用声纳,FWIW。

如果您使用 IntelliJ,默认情况下会发出警告

有关详细信息,请参阅 https://www.jetbrains.com/help/idea/list-of-java-inspections.html#code-maturity

我建议您使用服务器本身的 sonar server (community edition). There specific are rules for equals. There are plugins (SonarLint) to connect your favourite IDEs and also Plugins 来添加其他功能(如 spotbugs 等)。

(我不属于 sonarqube,而是免费声纳服务器的用户)

您也可以使用 spotbugs-maven-plugin,这会使构建失败并显示 RC:可疑引用比较 (RC_REF_COMPARISON) 如果遇到这样的代码.