|
1 |
| package net.sourceforge.pmd.rules.optimization; |
|
2 |
| |
|
3 |
| import java.util.Set; |
|
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 prefixSet = CollectionUtil.asSet(new String[] { |
|
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 suffixSet = CollectionUtil.asSet(new String[] { |
|
28 |
| "byteValue", |
|
29 |
| "shortValue", |
|
30 |
| "intValue", |
|
31 |
| "longValue", |
|
32 |
| "floatValue", |
|
33 |
| "doubleValue", |
|
34 |
| "charValue" |
|
35 |
| }); |
|
36 |
| |
|
37 |
6
| public Object visit(ASTPrimaryPrefix node, Object data) {
|
|
38 |
6
| if (node.jjtGetNumChildren() == 0 || !node.jjtGetChild(0).getClass().equals(ASTName.class)) {
|
|
39 |
0
| return super.visit(node, data);
|
|
40 |
| } |
|
41 |
| |
|
42 |
6
| String image = ((ASTName) node.jjtGetChild(0)).getImage();
|
|
43 |
6
| if (image.startsWith("java.lang.")) {
|
|
44 |
0
| image = image.substring(10);
|
|
45 |
| } |
|
46 |
| |
|
47 |
6
| boolean checkBoolean = ((RuleContext) data).getSourceType().compareTo(SourceType.JAVA_15) >= 0;
|
|
48 |
| |
|
49 |
6
| if (prefixSet.contains(image)||(checkBoolean && "Boolean.valueOf".equals(image))) {
|
|
50 |
3
| ASTPrimaryExpression parent = (ASTPrimaryExpression) node.jjtGetParent();
|
|
51 |
3
| if (parent.jjtGetNumChildren() >= 3) {
|
|
52 |
2
| Node n = parent.jjtGetChild(2);
|
|
53 |
2
| if (n instanceof ASTPrimarySuffix) {
|
|
54 |
2
| ASTPrimarySuffix suffix = (ASTPrimarySuffix) n;
|
|
55 |
2
| image = suffix.getImage();
|
|
56 |
| |
|
57 |
2
| if (suffixSet.contains(image)||(checkBoolean && "booleanValue".equals(image))) {
|
|
58 |
2
| super.addViolation(data, node);
|
|
59 |
2
| return data;
|
|
60 |
| } |
|
61 |
| } |
|
62 |
| } |
|
63 |
| } |
|
64 |
4
| return super.visit(node, data);
|
|
65 |
| } |
|
66 |
| |
|
67 |
| } |