View Javadoc

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