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