View Javadoc

    1   package net.sourceforge.pmd.lang.java.rule.naming;
    2
    3   import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
    4   import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator;
    5   import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
    6   import net.sourceforge.pmd.lang.java.ast.ASTResultType;
    7   import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
    8   import net.sourceforge.pmd.lang.ast.Node;
    9
    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 (t instanceof ASTPrimitiveType && "int".equals(t.getImage())) {
    31                  addViolation(data, node);
    32                  return data;
    33              }
    34          }
    35          return super.visit(node, data);
    36      }
    37
    38  }