01: package net.sourceforge.pmd.rules.optimization;
02:
03: import java.util.Set;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.RuleContext;
07: import net.sourceforge.pmd.SourceType;
08: import net.sourceforge.pmd.ast.ASTName;
09: 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<String> prefixSet = CollectionUtil
18: .asSet(new String[] { "Byte.valueOf", "Short.valueOf",
19: "Integer.valueOf", "Long.valueOf", "Float.valueOf",
20: "Double.valueOf", "Character.valueOf" });
21:
22: private static final Set<String> suffixSet = CollectionUtil
23: .asSet(new String[] { "byteValue", "shortValue",
24: "intValue", "longValue", "floatValue",
25: "doubleValue", "charValue" });
26:
27: public Object visit(ASTPrimaryPrefix node, Object data) {
28: if (node.jjtGetNumChildren() == 0
29: || !node.jjtGetChild(0).getClass()
30: .equals(ASTName.class)) {
31: return super .visit(node, data);
32: }
33:
34: String image = ((ASTName) node.jjtGetChild(0)).getImage();
35: if (image.startsWith("java.lang.")) {
36: image = image.substring(10);
37: }
38:
39: boolean checkBoolean = ((RuleContext) data).getSourceType()
40: .compareTo(SourceType.JAVA_15) >= 0;
41:
42: if (prefixSet.contains(image)
43: || (checkBoolean && "Boolean.valueOf".equals(image))) {
44: ASTPrimaryExpression parent = (ASTPrimaryExpression) node
45: .jjtGetParent();
46: if (parent.jjtGetNumChildren() >= 3) {
47: Node n = parent.jjtGetChild(2);
48: if (n instanceof ASTPrimarySuffix) {
49: ASTPrimarySuffix suffix = (ASTPrimarySuffix) n;
50: image = suffix.getImage();
51:
52: if (suffixSet.contains(image)
53: || (checkBoolean && "booleanValue"
54: .equals(image))) {
55: super.addViolation(data, node);
56: return data;
57: }
58: }
59: }
60: }
61: return super.visit(node, data);
62: }
63:
64: }
|