diff --git a/pmd/etc/changelog.txt b/pmd/etc/changelog.txt index 9f9c942e64..fb4b6a9493 100644 --- a/pmd/etc/changelog.txt +++ b/pmd/etc/changelog.txt @@ -2,6 +2,7 @@ Fixed bug 1618858 - PMD no longer raises an exception on XPath like '//ConditionalExpression//ConditionalExpression' Fixed bug 1626232 - Commons logging rules (ProperLogger and UseCorrectExceptionLogging) now catch more cases Fixed bug 1626201 - BrokenNullCheck now catches more cases +Applied patch 1612455 - RFE 1411022 CompareObjectsWithEquals now catches the case where comparison is against new Object December 19, 2006 - 3.9: New rules: diff --git a/pmd/regress/test/net/sourceforge/pmd/rules/design/xml/CompareObjectsWithEquals.xml b/pmd/regress/test/net/sourceforge/pmd/rules/design/xml/CompareObjectsWithEquals.xml index bb387628b9..76996181a3 100644 --- a/pmd/regress/test/net/sourceforge/pmd/rules/design/xml/CompareObjectsWithEquals.xml +++ b/pmd/regress/test/net/sourceforge/pmd/rules/design/xml/CompareObjectsWithEquals.xml @@ -109,4 +109,19 @@ public class Foo { } ]]> + + + 0 + + +} \ No newline at end of file diff --git a/pmd/src/net/sourceforge/pmd/rules/design/CompareObjectsWithEquals.java b/pmd/src/net/sourceforge/pmd/rules/design/CompareObjectsWithEquals.java index 0906e50f46..aa4025af9e 100644 --- a/pmd/src/net/sourceforge/pmd/rules/design/CompareObjectsWithEquals.java +++ b/pmd/src/net/sourceforge/pmd/rules/design/CompareObjectsWithEquals.java @@ -1,6 +1,7 @@ package net.sourceforge.pmd.rules.design; import net.sourceforge.pmd.AbstractRule; +import net.sourceforge.pmd.ast.ASTAllocationExpression; import net.sourceforge.pmd.ast.ASTEqualityExpression; import net.sourceforge.pmd.ast.ASTInitializer; import net.sourceforge.pmd.ast.ASTName; @@ -14,7 +15,25 @@ public class CompareObjectsWithEquals extends AbstractRule { return n.jjtGetNumChildren() > 0 && n.jjtGetChild(0) instanceof ASTName; } + /** + * Indicate whether this node is allocating a new object. + * + * @param n + * node that might be allocating a new object + * @return true if child 0 is an AllocationExpression + */ + private boolean isAllocation(Node n) { + return n.jjtGetNumChildren() > 0 && n.jjtGetChild(0) instanceof ASTAllocationExpression; + } + public Object visit(ASTEqualityExpression node, Object data) { + // If either side is allocating a new object, there's no way an + // equals expression is correct + if (isAllocation(node.jjtGetChild(0).jjtGetChild(0)) || isAllocation(node.jjtGetChild(1).jjtGetChild(0))) { + addViolation(data, node); + return data; + } + // skip if either child is not a simple name if (!hasName(((SimpleNode) node.jjtGetChild(0)).jjtGetChild(0)) || !hasName(((SimpleNode) node.jjtGetChild(1)).jjtGetChild(0))) { return data; diff --git a/pmd/xdocs/credits.xml b/pmd/xdocs/credits.xml index 0acf3d339e..6247619f56 100644 --- a/pmd/xdocs/credits.xml +++ b/pmd/xdocs/credits.xml @@ -56,7 +56,7 @@