Search code examples
javastatic-analysisprimitiveautoboxing

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


NPEs are described as a "billion dollar mistake". I have to believe a close second may be comparing boxed primitives with "==" instead of .equals(...).

When we have a part of our codebase that returns a Long instead of a long, for example:

class Car {
  Long speed;
}

and

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

this kind of thing is easy to miss in a PR. Is there a way to generate a warning to catch this situation? We use sonar, FWIW.


Solution

  • You could also use the spotbugs-maven-plugin which would make the build fail with RC: Suspicious reference comparison (RC_REF_COMPARISON) if it encounters code like this.