View Javadoc

    1   package net.sourceforge.pmd.lang.java.rule.finalizers;
    2
    3   import java.util.HashSet;
    4   import java.util.List;
    5   import java.util.Set;
    6
    7   import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
    8   import net.sourceforge.pmd.lang.java.ast.ASTName;
    9   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
    10  import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
    11  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
    12  import net.sourceforge.pmd.lang.java.symboltable.MethodScope;
    13
    14  public class AvoidCallingFinalizeRule extends AbstractJavaRule {
    15
    16      private Set<MethodScope> checked = new HashSet<MethodScope>();
    17
    18      public Object visit(ASTCompilationUnit acu, Object ctx) {
    19          checked.clear();
    20          return super.visit(acu, ctx);
    21      }
    22
    23      public Object visit(ASTName name, Object ctx) {
    24          if (name.getImage() == null ||  !name.getImage().endsWith("finalize")) {
    25              return ctx;
    26          }
    27          MethodScope meth = name.getScope().getEnclosingMethodScope();
    28          if (meth.getName().equals("finalize")) {
    29              return ctx;
    30          }
    31          if (checked.contains(meth)) {
    32              return ctx;
    33          }
    34          checked.add(meth);
    35          addViolation(ctx, name);
    36          return ctx;
    37      }
    38
    39      public Object visit(ASTPrimaryPrefix pp, Object ctx) {
    40          List<ASTPrimarySuffix> primarySuffixes = pp.jjtGetParent().findChildrenOfType(ASTPrimarySuffix.class);
    41          ASTPrimarySuffix firstSuffix = null;
    42          if (primarySuffixes.size() > 0) {
    43              firstSuffix = primarySuffixes.get(0);
    44          }
    45          if (firstSuffix == null || firstSuffix.getImage() == null || !firstSuffix.getImage().endsWith("finalize")) {
    46              return super.visit(pp, ctx);
    47          }
    48          MethodScope meth = pp.getScope().getEnclosingMethodScope();
    49          if (meth.getName().equals("finalize")) {
    50              return super.visit(pp, ctx);
    51          }
    52          if (checked.contains(meth)) {
    53              return super.visit(pp, ctx);
    54          }
    55          checked.add(meth);
    56          addViolation(ctx, pp);
    57          return super.visit(pp, ctx);
    58      }
    59  }