Standard Analyses

SemmleCode Professional comes with a wide range of pre-packaged analyses, from architectural properties and metrics, to statement-level checks for likely bugs and violations of best practice.


Equals on Incomparable Types

This query finds calls of the form x.equals(y), where x and y have incomparable types, i.e. their types are not the same, and they do not have a common subtype.

This means that the runtime types of x and y will be different, and hence the equality test will most likely always fail.

How to Interpret the Query Results

The query flags all expressions of this form and provides a list of all detected occurrences in the results view.

How to Address the Query Results

Carefully check all flagged expressions to ensure that they are not typos.

Source Code
import default

from EqualsMethod equals,
     MethodAccess ma, 
     RefType i, 
     RefType j
where 
      ma.getMethod() = equals and

      // find the source types
      ma.getArgument(0).getType()  =  i and
      ma.getQualifier().getType() = j and
      
      // check they are not related
      not exists(RefType k | k.getASupertype*() = j and
                             k.getASupertype*() = i)
select ma, "Call to equals() comparing incomparable types "
           + j.getName() + " and " + i.getName()
References