1 6 package net.sourceforge.pmd.rules; 7 8 import net.sourceforge.pmd.AbstractRule; 9 import net.sourceforge.pmd.ast.ASTConstructorDeclaration; 10 import net.sourceforge.pmd.ast.ASTFieldDeclaration; 11 import net.sourceforge.pmd.ast.ASTInitializer; 12 import net.sourceforge.pmd.ast.ASTMethodDeclaration; 13 import net.sourceforge.pmd.ast.ASTVariableDeclaratorId; 14 import net.sourceforge.pmd.ast.SimpleNode; 15 import net.sourceforge.pmd.symboltable.NameOccurrence; 16 17 import java.util.List ; 18 19 22 public class SingularField extends AbstractRule { 23 24 public Object visit(ASTFieldDeclaration node, Object data) { 25 if (node.isPrivate() && !node.isStatic()) { 26 List list = node.findChildrenOfType(ASTVariableDeclaratorId.class); 27 ASTVariableDeclaratorId declaration = (ASTVariableDeclaratorId) list.get(0); 28 List usages = declaration.getUsages(); 29 SimpleNode decl = null; 30 boolean violation = true; 31 for (int ix = 0; ix < usages.size(); ix++) { 32 NameOccurrence no = (NameOccurrence) usages.get(ix); 33 SimpleNode location = no.getLocation(); 34 35 SimpleNode method = (SimpleNode) location.getFirstParentOfType(ASTMethodDeclaration.class); 36 if (method == null) { 37 method = (SimpleNode) location.getFirstParentOfType(ASTConstructorDeclaration.class); 38 if (method == null) { 39 method = (SimpleNode) location.getFirstParentOfType(ASTInitializer.class); 40 if (method == null) { 41 continue; 42 } 43 } 44 } 45 46 if (decl == null) { 47 decl = method; 48 continue; 49 } else if (decl != method) { 50 51 violation = false; 52 } 53 } 54 55 if (violation && !usages.isEmpty()) { 56 addViolation(data, node, new Object [] { declaration.getImage() }); 57 } 58 } 59 return data; 60 } 61 } 62 | Popular Tags |