View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.symboltable;
5   
6   import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
7   import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
8   import net.sourceforge.pmd.util.UnaryFunction;
9   
10  public class DeclarationFinderFunction implements UnaryFunction<NameDeclaration> {
11  
12      private NameOccurrence occurrence;
13      private NameDeclaration decl;
14  
15      public DeclarationFinderFunction(NameOccurrence occurrence) {
16          this.occurrence = occurrence;
17      }
18  
19      public void applyTo(NameDeclaration nameDeclaration) {
20          if (isDeclaredBefore(nameDeclaration) && isSameName(nameDeclaration)) {
21              decl = nameDeclaration;
22          }
23      }
24  
25      private boolean isDeclaredBefore(NameDeclaration nameDeclaration) {
26          if (nameDeclaration.getNode() != null && occurrence.getLocation() != null) {
27              return nameDeclaration.getNode().getBeginLine() <=
28                      occurrence.getLocation().getBeginLine();
29          }
30  
31          return true;
32      }
33  
34      private boolean isSameName(NameDeclaration nameDeclaration) {
35          return occurrence.getImage().equals(nameDeclaration.getName());
36      }
37  
38      public NameDeclaration getDecl() {
39          return this.decl;
40      }
41  }