View Javadoc

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