KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > UnusedPrivateFieldRule


1 /**
2  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3  */

4 package net.sourceforge.pmd.rules;
5
6 import net.sourceforge.pmd.AbstractRule;
7 import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
8 import net.sourceforge.pmd.symboltable.NameOccurrence;
9 import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
10
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13 import java.util.Map JavaDoc;
14
15 public class UnusedPrivateFieldRule extends AbstractRule {
16
17     public Object JavaDoc visit(ASTClassOrInterfaceDeclaration node, Object JavaDoc data) {
18         Map JavaDoc vars = node.getScope().getVariableDeclarations();
19         for (Iterator JavaDoc i = vars.entrySet().iterator(); i.hasNext();) {
20             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
21             VariableNameDeclaration decl = (VariableNameDeclaration) entry.getKey();
22             if (!decl.getAccessNodeParent().isPrivate() || isOK(decl.getImage())) {
23                 continue;
24             }
25             if (!actuallyUsed((List JavaDoc) entry.getValue())) {
26                 addViolation(data, decl.getNode(), decl.getImage());
27             }
28         }
29         return super.visit(node, data);
30     }
31
32     private boolean actuallyUsed(List JavaDoc usages) {
33         for (Iterator JavaDoc j = usages.iterator(); j.hasNext();) {
34             NameOccurrence nameOccurrence = (NameOccurrence) j.next();
35             if (!nameOccurrence.isOnLeftHandSide()) {
36                 return true;
37             }
38         }
39         return false;
40     }
41
42     private boolean isOK(String JavaDoc image) {
43         return image.equals("serialVersionUID") || image.equals("serialPersistentFields") || image.equals("IDENT");
44     }
45 }
46
Popular Tags