KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > strings > StringInstantiation


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