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