View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.rules.strings;
    5
    6   import net.sourceforge.pmd.AbstractRule;
    7   import net.sourceforge.pmd.ast.ASTName;
    8   import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
    9   import net.sourceforge.pmd.symboltable.NameOccurrence;
    10  import net.sourceforge.pmd.typeresolution.TypeHelper;
    11
    12  public class StringToStringRule extends AbstractRule {
    13
    14      public Object visit(ASTVariableDeclaratorId node, Object data) {
    15          if (!TypeHelper.isA(node.getNameDeclaration(), String.class)) {
    16              return data;
    17          }
    18          boolean isArray = node.isArray();
    19          for (NameOccurrence occ: node.getUsages()) {
    20              NameOccurrence qualifier = occ.getNameForWhichThisIsAQualifier();
    21              if (qualifier != null) {
    22                  if (!isArray && qualifier.getImage().indexOf("toString") != -1) {
    23                      addViolation(data, occ.getLocation());
    24                  } else if (isArray && qualifier.getLocation() != null && !ASTName.class.equals(qualifier.getLocation().getClass()) && qualifier.getImage().equals("toString")) {
    25                      addViolation(data, occ.getLocation());
    26                  }
    27              }
    28          }
    29          return data;
    30      }
    31  }