KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > design > AssignmentToNonFinalStatic


1 /*
2  * AssignmentToNonFinalStaticRule.java
3  *
4  * Created on October 24, 2004, 8:56 AM
5  */

6
7 package net.sourceforge.pmd.rules.design;
8
9 import net.sourceforge.pmd.AbstractRule;
10 import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
11 import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
12 import net.sourceforge.pmd.ast.SimpleNode;
13 import net.sourceforge.pmd.symboltable.NameOccurrence;
14 import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
15
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Map JavaDoc;
19
20
21 /**
22  * @author Eric Olander
23  */

24 public class AssignmentToNonFinalStatic extends AbstractRule {
25
26     public Object JavaDoc visit(ASTClassOrInterfaceDeclaration node, Object JavaDoc data) {
27         Map JavaDoc vars = node.getScope().getVariableDeclarations();
28         for (Iterator JavaDoc i = vars.entrySet().iterator(); i.hasNext();) {
29             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
30             VariableNameDeclaration decl = (VariableNameDeclaration) entry.getKey();
31             if (!decl.getAccessNodeParent().isStatic() || decl.getAccessNodeParent().isFinal()) {
32                 continue;
33             }
34
35             if (initializedInConstructor((List JavaDoc) entry.getValue())) {
36                 addViolation(data, decl.getNode(), decl.getImage());
37             }
38         }
39         return super.visit(node, data);
40     }
41
42     private boolean initializedInConstructor(List JavaDoc usages) {
43         boolean initInConstructor = false;
44
45         for (Iterator JavaDoc j = usages.iterator(); j.hasNext();) {
46             NameOccurrence occ = (NameOccurrence) j.next();
47             if (occ.isOnLeftHandSide()) { // specifically omitting prefix and postfix operators as there are legitimate usages of these with static fields, e.g. typesafe enum pattern.
48
SimpleNode node = occ.getLocation();
49                 SimpleNode constructor = (SimpleNode) node.getFirstParentOfType(ASTConstructorDeclaration.class);
50                 if (constructor != null) {
51                     initInConstructor = true;
52                 }
53             }
54         }
55
56         return initInConstructor;
57     }
58
59 }
60
Popular Tags