diff --git a/pmd/etc/changelog.txt b/pmd/etc/changelog.txt index 386f458043..40f7cf9664 100644 --- a/pmd/etc/changelog.txt +++ b/pmd/etc/changelog.txt @@ -8,6 +8,7 @@ Fixed bug 1989814 - false +: ConsecutiveLiteralAppends Fixed bug 1977230 - false positive: UselessOverridingMethod Fixed bug 1998185 - BeanMembersShouldSerialize vs @SuppressWarnings("serial") Fixed bug 2002722 - false + in UseStringBufferForStringAppends +Fixed bug 2056318 - False positive for AvoidInstantiatingObjectsInLoops Optimizations and false positive fixes in PreserveStackTrace @SuppressWarnings("all") disables all warnings diff --git a/pmd/regress/test/net/sourceforge/pmd/rules/optimizations/xml/AvoidInstantiatingObjectsInLoops.xml b/pmd/regress/test/net/sourceforge/pmd/rules/optimizations/xml/AvoidInstantiatingObjectsInLoops.xml index e8e9cf632e..8d3d1a0554 100644 --- a/pmd/regress/test/net/sourceforge/pmd/rules/optimizations/xml/AvoidInstantiatingObjectsInLoops.xml +++ b/pmd/regress/test/net/sourceforge/pmd/rules/optimizations/xml/AvoidInstantiatingObjectsInLoops.xml @@ -88,6 +88,22 @@ public class Foo { return new String(); } } +} + ]]> + + + + 0 + diff --git a/pmd/src/net/sourceforge/pmd/rules/optimization/AvoidInstantiatingObjectsInLoops.java b/pmd/src/net/sourceforge/pmd/rules/optimization/AvoidInstantiatingObjectsInLoops.java index c07487e4c9..8a90b9b9d3 100644 --- a/pmd/src/net/sourceforge/pmd/rules/optimization/AvoidInstantiatingObjectsInLoops.java +++ b/pmd/src/net/sourceforge/pmd/rules/optimization/AvoidInstantiatingObjectsInLoops.java @@ -5,10 +5,12 @@ package net.sourceforge.pmd.rules.optimization; import net.sourceforge.pmd.ast.ASTAllocationExpression; import net.sourceforge.pmd.ast.ASTDoStatement; +import net.sourceforge.pmd.ast.ASTForInit; import net.sourceforge.pmd.ast.ASTForStatement; import net.sourceforge.pmd.ast.ASTReturnStatement; import net.sourceforge.pmd.ast.ASTThrowStatement; import net.sourceforge.pmd.ast.ASTWhileStatement; +import net.sourceforge.pmd.ast.Node; public class AvoidInstantiatingObjectsInLoops extends AbstractOptimizationRule { @@ -28,14 +30,21 @@ public class AvoidInstantiatingObjectsInLoops extends AbstractOptimizationRule { } private boolean insideLoop(ASTAllocationExpression node) { - if (node.getFirstParentOfType(ASTDoStatement.class) != null) { - return true; - } - if (node.getFirstParentOfType(ASTWhileStatement.class) != null) { - return true; - } - if (node.getFirstParentOfType(ASTForStatement.class) != null) { - return true; + Node n = node.jjtGetParent(); + while (n != null) { + if (n instanceof ASTDoStatement || + n instanceof ASTWhileStatement || + n instanceof ASTForStatement) { + return true; + } else if (n instanceof ASTForInit) { + /* + * init part is not technically inside the loop. + * Skip parent ASTForStatement but continue higher + * up to detect nested loops + */ + n = n.jjtGetParent(); + } + n = n.jjtGetParent(); } return false; }