Is there any tool that can warn me against the following sort of code:
if ( someClass.equals( someString ))
For example:
if ( myObject.getClass().equals( myClassName ))
Such a thing is legal Java (equals takes an Object) but will never evaluate to true (a class can never equal a String) so is almost certainly a bug.
I have checked Eclipse, FindBugs and PMD but none seem to support this feature?
Yes, IntelliJ IDEA has such an inspection that I believe is enabled by default. It flags the following:
Class<?> clazz = String.class;
if (clazz.equals("foo")) {
//...
}
With the warning:
'equals()' between objects of inconvertible types.
The inspection can be enabled/disabled through Settings->Project Settings->Inspections, then under Probable Bugs check/uncheck "'equals()' between objects of inconvertible types."
FindBugs also should catch this with the "EC: Call to equals() comparing different types" bug check. It can be integrated with Eclipse as it appears you are aware.
Neither is a silver bullet though; they can't read your mind. The best you can hope for is that it will favour false positives rather than false negatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With