View Javadoc

1   package net.sourceforge.pmd.rules;
2   
3   import net.sourceforge.pmd.AbstractRule;
4   import net.sourceforge.pmd.ast.ASTAllocationExpression;
5   import net.sourceforge.pmd.ast.ASTArrayDimsAndInits;
6   import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
7   import net.sourceforge.pmd.ast.ASTExpression;
8   import net.sourceforge.pmd.ast.ASTName;
9   import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
10  
11  import java.util.List;
12  
13  public class StringInstantiation extends AbstractRule {
14  
15      public Object visit(ASTAllocationExpression node, Object data) {
16          if (!(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) {
17              return data;
18          }
19  
20          ASTClassOrInterfaceType clz = (ASTClassOrInterfaceType)node.jjtGetChild(0);
21          if (!clz.getImage().equals("String")) {
22              return data;
23          }
24  
25          List exp = node.findChildrenOfType(ASTExpression.class);
26          if (exp.size() >=2 ){
27              return data;
28          }
29  
30          if (node.getFirstChildOfType(ASTArrayDimsAndInits.class) != null) {
31              return data;
32          }
33  
34          ASTName name = (ASTName)node.getFirstChildOfType(ASTName.class);
35          if (name == null) { // Literal, i.e., new String("foo")
36              addViolation(data, node);
37              return data;
38          }
39  
40          VariableNameDeclaration nd = (VariableNameDeclaration)name.getNameDeclaration();
41          // nd == null in cases like: return new String("foo");
42          if (nd == null || nd.getTypeImage().equals("String")) {
43              addViolation(data, node);
44  
45          }
46          return data;
47      }
48  }