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.strings;
5   
6   import net.sourceforge.pmd.lang.java.ast.ASTName;
7   import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
8   import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
9   import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
10  import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
11  
12  public class StringToStringRule extends AbstractJavaRule {
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 && !(qualifier.getLocation() instanceof ASTName) && qualifier.getImage().equals("toString")) {
25                      addViolation(data, occ.getLocation());
26                  }
27              }
28          }
29          return data;
30      }
31  }