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.LanguageRegistry;
10  import net.sourceforge.pmd.lang.java.JavaLanguageModule;
11  import net.sourceforge.pmd.lang.java.ast.ASTName;
12  import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
13  import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
14  import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
15  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
16  import net.sourceforge.pmd.lang.ast.Node;
17  import net.sourceforge.pmd.util.CollectionUtil;
18  
19  public class UnnecessaryWrapperObjectCreationRule extends AbstractJavaRule {
20  
21      private static final Set<String> PREFIX_SET = CollectionUtil.asSet(new String[] { "Byte.valueOf", "Short.valueOf",
22              "Integer.valueOf", "Long.valueOf", "Float.valueOf", "Double.valueOf", "Character.valueOf" });
23  
24      private static final Set<String> SUFFIX_SET = CollectionUtil.asSet(new String[] { "toString", "byteValue",
25              "shortValue", "intValue", "longValue", "floatValue", "doubleValue", "charValue" });
26  
27      public Object visit(ASTPrimaryPrefix node, Object data) {
28          if (node.jjtGetNumChildren() == 0 || !(node.jjtGetChild(0) instanceof ASTName)) {
29              return super.visit(node, data);
30          }
31  
32          String image = ((ASTName) node.jjtGetChild(0)).getImage();
33          if (image.startsWith("java.lang.")) {
34              image = image.substring(10);
35          }
36  
37          boolean checkBoolean = ((RuleContext) data).getLanguageVersion().compareTo(
38                  LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getVersion("1.5")) >= 0;
39  
40          if (PREFIX_SET.contains(image) || checkBoolean && "Boolean.valueOf".equals(image)) {
41              ASTPrimaryExpression parent = (ASTPrimaryExpression) node.jjtGetParent();
42              if (parent.jjtGetNumChildren() >= 3) {
43                  Node n = parent.jjtGetChild(2);
44                  if (n instanceof ASTPrimarySuffix) {
45                      ASTPrimarySuffix suffix = (ASTPrimarySuffix) n;
46                      image = suffix.getImage();
47  
48                      if (SUFFIX_SET.contains(image) || checkBoolean && "booleanValue".equals(image)) {
49                          super.addViolation(data, node);
50                          return data;
51                      }
52                  }
53              }
54          }
55          return super.visit(node, data);
56      }
57  
58  }