KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > optimization > UnnecessaryWrapperObjectCreation


1 package net.sourceforge.pmd.rules.optimization;
2
3 import java.util.Set JavaDoc;
4
5 import net.sourceforge.pmd.AbstractRule;
6 import net.sourceforge.pmd.RuleContext;
7 import net.sourceforge.pmd.SourceType;
8 import net.sourceforge.pmd.ast.ASTName;
9 import net.sourceforge.pmd.ast.ASTPrimaryExpression;
10 import net.sourceforge.pmd.ast.ASTPrimaryPrefix;
11 import net.sourceforge.pmd.ast.ASTPrimarySuffix;
12 import net.sourceforge.pmd.ast.Node;
13 import net.sourceforge.pmd.util.CollectionUtil;
14
15 public class UnnecessaryWrapperObjectCreation extends AbstractRule {
16
17     private static final Set JavaDoc prefixSet = CollectionUtil.asSet(new String JavaDoc[] {
18         "Byte.valueOf",
19         "Short.valueOf",
20         "Integer.valueOf",
21         "Long.valueOf",
22         "Float.valueOf",
23         "Double.valueOf",
24         "Character.valueOf"
25     });
26
27     private static final Set JavaDoc suffixSet = CollectionUtil.asSet(new String JavaDoc[] {
28         "byteValue",
29         "shortValue",
30         "intValue",
31         "longValue",
32         "floatValue",
33         "doubleValue",
34         "charValue"
35     });
36
37     public Object JavaDoc visit(ASTPrimaryPrefix node, Object JavaDoc data) {
38         if (node.jjtGetNumChildren() == 0 || !node.jjtGetChild(0).getClass().equals(ASTName.class)) {
39             return super.visit(node, data);
40         }
41
42         String JavaDoc image = ((ASTName) node.jjtGetChild(0)).getImage();
43         if (image.startsWith("java.lang.")) {
44             image = image.substring(10);
45         }
46
47         boolean checkBoolean = ((RuleContext) data).getSourceType().compareTo(SourceType.JAVA_15) >= 0;
48
49         if (prefixSet.contains(image)||(checkBoolean && "Boolean.valueOf".equals(image))) {
50             ASTPrimaryExpression parent = (ASTPrimaryExpression) node.jjtGetParent();
51             if (parent.jjtGetNumChildren() >= 3) {
52                 Node n = parent.jjtGetChild(2);
53                 if (n instanceof ASTPrimarySuffix) {
54                     ASTPrimarySuffix suffix = (ASTPrimarySuffix) n;
55                     image = suffix.getImage();
56
57                     if (suffixSet.contains(image)||(checkBoolean && "booleanValue".equals(image))) {
58                         super.addViolation(data, node);
59                         return data;
60                     }
61                 }
62             }
63         }
64         return super.visit(node, data);
65     }
66
67 }
68
Popular Tags