diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java index 5de801930..dc2aadb4b 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/EqualsAvoidNullRule.java @@ -26,6 +26,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTLiteral; import net.sourceforge.pmd.lang.java.ast.ASTName; +import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode; @@ -61,6 +62,11 @@ public Object visit(ASTCompilationUnit node, Object data) { return super.visit(node, data); } for (Node invocation : equalsInvocations) { + // https://github.com/alibaba/p3c/issues/471 + if (callerIsLiteral(invocation)) { + return super.visit(node, data); + } + // if arguments of equals is complicate expression, skip the check List simpleExpressions = invocation.findChildNodesWithXPath(INVOCATION_PREFIX_XPATH); if (simpleExpressions == null || simpleExpressions.isEmpty()) { @@ -98,6 +104,14 @@ public Object visit(ASTCompilationUnit node, Object data) { return super.visit(node, data); } + private boolean callerIsLiteral(Node equalsInvocation) { + if (equalsInvocation instanceof ASTPrimaryExpression) { + ASTPrimaryPrefix caller = equalsInvocation.getFirstChildOfType(ASTPrimaryPrefix.class); + return caller != null && caller.getFirstChildOfType(ASTLiteral.class) != null; + } + return false; + } + private String getInvocationName(AbstractJavaNode javaNode) { Token token = (Token)javaNode.jjtGetFirstToken(); StringBuilder sb = new StringBuilder(token.image).append(token.image); diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml index 3d1e959f0..54cedb410 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml @@ -129,4 +129,41 @@ 0 + + + + + + + + string literal equals constant + 0 + + + + + + + + + + string literal equals string literal + 0 + + + + \ No newline at end of file