View Javadoc

    1   package net.sourceforge.pmd.lang.java.rule.optimizations;
    2
    3   import java.util.Set;
    4
    5   import net.sourceforge.pmd.RuleContext;
    6   import net.sourceforge.pmd.lang.java.ast.ASTName;
    7   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
    8   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
    9   import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
    10  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
    11  import net.sourceforge.pmd.lang.LanguageVersion;
    12  import net.sourceforge.pmd.lang.ast.Node;
    13  import net.sourceforge.pmd.util.CollectionUtil;
    14
    15  public class UnnecessaryWrapperObjectCreationRule extends AbstractJavaRule {
    16
    17      private static final Set<String> PREFIX_SET = 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> SUFFIX_SET = 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) instanceof ASTName)) {
    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).getLanguageVersion().compareTo(LanguageVersion.JAVA_15) >= 0;
    49
    50          if (PREFIX_SET.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 (SUFFIX_SET.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  }