Skip to content

Commit

Permalink
Prevent EqualsAvoidsNull from rewriting aString.equals(null) into nul…
Browse files Browse the repository at this point in the history
…l.equals(aString)
  • Loading branch information
sambsnyd committed Aug 8, 2024
1 parent 6d04813 commit 79f4dfa
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,16 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, P p)
}

if ((STRING_EQUALS.matches(m) || (!Boolean.TRUE.equals(style.getIgnoreEqualsIgnoreCase()) && STRING_EQUALS_IGNORE_CASE.matches(m))) &&
m.getArguments().get(0) instanceof J.Literal &&
!(m.getSelect() instanceof J.Literal)) {
m.getArguments().get(0) instanceof J.Literal &&
m.getArguments().get(0).getType() != JavaType.Primitive.Null &&
!(m.getSelect() instanceof J.Literal)) {
Tree parent = getCursor().getParentTreeCursor().getValue();
if (parent instanceof J.Binary) {
J.Binary binary = (J.Binary) parent;
if (binary.getOperator() == J.Binary.Type.And && binary.getLeft() instanceof J.Binary) {
J.Binary potentialNullCheck = (J.Binary) binary.getLeft();
if ((isNullLiteral(potentialNullCheck.getLeft()) && matchesSelect(potentialNullCheck.getRight(), m.getSelect())) ||
(isNullLiteral(potentialNullCheck.getRight()) && matchesSelect(potentialNullCheck.getLeft(), m.getSelect()))) {
(isNullLiteral(potentialNullCheck.getRight()) && matchesSelect(potentialNullCheck.getLeft(), m.getSelect()))) {
doAfterVisit(new RemoveUnnecessaryNullCheck<>(binary));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,19 @@ public class A {
)
);
}

@Test
void nullLiteral() {
rewriteRun(
//language=java
java("""
public class A {
void foo(String s) {
if(s.equals(null)) {
}
}
}
""")
);
}
}

0 comments on commit 79f4dfa

Please sign in to comment.