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.JavaNameOccurrence;
10  import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
11  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
12  
13  public class StringToStringRule extends AbstractJavaRule {
14  
15      public Object visit(ASTVariableDeclaratorId node, Object data) {
16          if (!TypeHelper.isA(node.getNameDeclaration(), String.class)) {
17              return data;
18          }
19          boolean isArray = node.isArray();
20          for (NameOccurrence occ: node.getUsages()) {
21              JavaNameOccurrence jocc = (JavaNameOccurrence)occ;
22              NameOccurrence qualifier = jocc.getNameForWhichThisIsAQualifier();
23              if (qualifier != null) {
24                  if (!isArray && qualifier.getImage().indexOf("toString") != -1) {
25                      addViolation(data, jocc.getLocation());
26                  } else if (isArray && qualifier.getLocation() != null && !(qualifier.getLocation() instanceof ASTName) && qualifier.getImage().equals("toString")) {
27                      addViolation(data, jocc.getLocation());
28                  }
29              }
30          }
31          return data;
32      }
33  }