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.rule.naming;
5   
6   import java.util.ArrayList;
7   import java.util.HashSet;
8   import java.util.List;
9   import java.util.Set;
10  
11  import net.sourceforge.pmd.lang.ast.Node;
12  import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBody;
13  import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
14  import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
15  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
16  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
17  
18  public class AvoidFieldNameMatchingMethodNameRule extends AbstractJavaRule {
19  
20      @Override
21      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
22          if (node.isInterface()) {
23              return data;
24          }
25          return super.visit(node, data);
26      }
27  
28      @Override
29      public Object visit(ASTClassOrInterfaceBody node, Object data) {
30          int n = node.jjtGetNumChildren();
31          List<ASTFieldDeclaration> fields = new ArrayList<>();
32          Set<String> methodNames = new HashSet<>();
33          for (int i = 0; i < n; i++) {
34              Node child = node.jjtGetChild(i);
35              if (child.jjtGetNumChildren() == 0) {
36                  continue;
37              }
38              child = child.jjtGetChild(child.jjtGetNumChildren()-1);
39              if (child instanceof ASTFieldDeclaration) {
40                  fields.add((ASTFieldDeclaration) child);
41              } else if (child instanceof ASTMethodDeclaration) {
42                  methodNames.add(((ASTMethodDeclaration) child).getMethodName().toLowerCase());
43              }
44          }
45          for (ASTFieldDeclaration field : fields) {
46              String varName = field.getVariableName().toLowerCase();
47              if (methodNames.contains(varName)) {
48                  addViolation(data, field, field.getVariableName());
49              }
50          }
51          return super.visit(node, data);
52      }
53  
54  }