View Javadoc

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