|
1 |
| |
|
2 |
| |
|
3 |
| |
|
4 |
| |
|
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; |
|
17 |
| import java.util.List; |
|
18 |
| import java.util.Map; |
|
19 |
| |
|
20 |
| |
|
21 |
| |
|
22 |
| |
|
23 |
| |
|
24 |
| public class AssignmentToNonFinalStatic extends AbstractRule { |
|
25 |
| |
|
26 |
2
| public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
|
|
27 |
2
| Map vars = node.getScope().getVariableDeclarations();
|
|
28 |
2
| for (Iterator i = vars.entrySet().iterator(); i.hasNext();) {
|
|
29 |
2
| Map.Entry entry = (Map.Entry) i.next();
|
|
30 |
2
| VariableNameDeclaration decl = (VariableNameDeclaration) entry.getKey();
|
|
31 |
2
| if (!decl.getAccessNodeParent().isStatic() || decl.getAccessNodeParent().isFinal()) {
|
|
32 |
1
| continue;
|
|
33 |
| } |
|
34 |
| |
|
35 |
1
| if (initializedInConstructor((List) entry.getValue())) {
|
|
36 |
1
| addViolation(data, decl.getNode(), decl.getImage());
|
|
37 |
| } |
|
38 |
| } |
|
39 |
2
| return super.visit(node, data);
|
|
40 |
| } |
|
41 |
| |
|
42 |
1
| private boolean initializedInConstructor(List usages) {
|
|
43 |
1
| boolean initInConstructor = false;
|
|
44 |
| |
|
45 |
1
| for (Iterator j = usages.iterator(); j.hasNext();) {
|
|
46 |
1
| NameOccurrence occ = (NameOccurrence) j.next();
|
|
47 |
1
| if (occ.isOnLeftHandSide()) {
|
|
48 |
1
| SimpleNode node = occ.getLocation();
|
|
49 |
1
| SimpleNode constructor = (SimpleNode) node.getFirstParentOfType(ASTConstructorDeclaration.class);
|
|
50 |
1
| if (constructor != null) {
|
|
51 |
1
| initInConstructor = true;
|
|
52 |
| } |
|
53 |
| } |
|
54 |
| } |
|
55 |
| |
|
56 |
1
| return initInConstructor;
|
|
57 |
| } |
|
58 |
| |
|
59 |
| } |