Merge branch 'bug-1428' into pmd/5.4.x

This commit is contained in:
Andreas Dangel
2015-10-10 19:00:18 +02:00
4 changed files with 71 additions and 2 deletions

View File

@ -0,0 +1,41 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symboltable;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
import net.sourceforge.pmd.util.UnaryFunction;
public class DeclarationFinderFunction implements UnaryFunction<NameDeclaration> {
private NameOccurrence occurrence;
private NameDeclaration decl;
public DeclarationFinderFunction(NameOccurrence occurrence) {
this.occurrence = occurrence;
}
public void applyTo(NameDeclaration nameDeclaration) {
if (isDeclaredBefore(nameDeclaration) && isSameName(nameDeclaration)) {
decl = nameDeclaration;
}
}
private boolean isDeclaredBefore(NameDeclaration nameDeclaration) {
if (nameDeclaration.getNode() != null && occurrence.getLocation() != null) {
return nameDeclaration.getNode().getBeginLine() <=
occurrence.getLocation().getBeginLine();
}
return true;
}
private boolean isSameName(NameDeclaration nameDeclaration) {
return occurrence.getImage().equals(nameDeclaration.getName());
}
public NameDeclaration getDecl() {
return this.decl;
}
}

View File

@ -53,7 +53,7 @@ public class LocalScope extends AbstractJavaScope {
if (occurrence.isThisOrSuper() || occurrence.isMethodOrConstructorInvocation()) {
return result;
}
ImageFinderFunction finder = new ImageFinderFunction(occurrence.getImage());
DeclarationFinderFunction finder = new DeclarationFinderFunction(occurrence);
Applier.apply(finder, getVariableDeclarations().keySet().iterator());
if (finder.getDecl() != null) {
result.add(finder.getDecl());

View File

@ -533,6 +533,31 @@ public class Foo {
@Data
public class Foo {
private String bar;
}
]]></code>
</test-code>
<test-code>
<description>#1428 False positive in UnusedPrivateField when local variable hides member variable</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class IssueUnusedPrivateField {
private static Object helper; // PMD warns unused
@BeforeClass
public static void setUpClass() {
helper = new Object();
}
@Test
public void testSomething() {
String str = helper.toString(); // used here
System.out.println("str = " + str);
String helper = "some new string"; // hidden here
System.out.println("helper = " + helper);
}
}
]]></code>
</test-code>