Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anything warn me against type.equals(incompatibleType)?

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?

like image 400
Richard Kennard Avatar asked Oct 26 '11 02:10

Richard Kennard


1 Answers

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.

like image 143
Mark Peters Avatar answered Oct 04 '22 01:10

Mark Peters