equals casts its argument without checking its type, throwing instead of returning false
What it finds
equals(Object other) that casts other without first checking its class throws a ClassCastException when it is given an object of another type, where the contract asks for false. Collections and Objects.equals compare objects of mixed types all the time. other instanceof Point p or a getClass() comparison checks first.
Reported are equals methods that cast their parameter and contain no instanceof, no call of getClass or isInstance, and no catch clause.
From the rule's source, equals_unchecked_cast.rs.
class Point { int x; @Override public boolean equals(Object o) { Point p = (Point) o;tx0 reports: the argument is cast without checking its type return p.x == x; } @Override public int hashCode() { return x; }} class Size { int w; @Override public boolean equals(Object o) { if (!(o instanceof Size)) { return false; } return ((Size) o).w == w; } @Override public int hashCode() { return w; }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:equals-unchecked-cast" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:equals-unchecked-cast] reason="..."tx0 explain tx0/java:equals-unchecked-cast shows the same in the terminal. Found a false positive? Report it.