Fixed bug 2056318 - False positive for AvoidInstantiatingObjectsInLoops

git-svn-id: https://pmd.svn.sourceforge.net/svnroot/pmd/branches/pmd/4.2.x@6370 51baf565-9d33-0410-a72c-fc3788e3496d
This commit is contained in:
Xavier Le Vourch 2008-08-19 22:18:34 +00:00
parent 8a0052dee9
commit 5620b24c8f
3 changed files with 34 additions and 8 deletions

View File

@ -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

View File

@ -88,6 +88,22 @@ public class Foo {
return new String();
}
}
}
]]></code>
</test-code>
<test-code>
<description><![CDATA[
[ 2056318 ] False positive for AvoidInstantiatingObjectsInLoops
]]></description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class Foo {
public void test1() {
Object o;
int i;
for(o = new Object(), i = 0; i < 10; i++) {
}
}
}
]]></code>
</test-code>

View File

@ -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;
}