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 net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
7   import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator;
8   import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
9   import net.sourceforge.pmd.lang.java.ast.ASTResultType;
10  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
11  import net.sourceforge.pmd.lang.ast.Node;
12  
13  public class SuspiciousHashcodeMethodNameRule extends AbstractJavaRule {
14  
15      public Object visit(ASTMethodDeclaration node, Object data) {
16          /* original XPath rule was
17           //MethodDeclaration
18          [ResultType
19          //PrimitiveType
20          [@Image='int']
21          [//MethodDeclarator
22          [@Image='hashcode' or @Image='HashCode' or @Image='Hashcode']
23          [not(FormalParameters/*)]]]
24           */
25  
26          ASTResultType type = node.getResultType();
27          ASTMethodDeclarator decl = node.getFirstChildOfType(ASTMethodDeclarator.class);
28          String name = decl.getImage();
29          if (name.equalsIgnoreCase("hashcode") && !name.equals("hashCode")
30                  && decl.jjtGetChild(0).jjtGetNumChildren() == 0
31                  && type.jjtGetNumChildren() != 0) {
32              Node t = type.jjtGetChild(0).jjtGetChild(0);
33              if (t instanceof ASTPrimitiveType && "int".equals(t.getImage())) {
34                  addViolation(data, node);
35                  return data;
36              }
37          }
38          return super.visit(node, data);
39      }
40  
41  }