KickJava   Java API By Example, From Geeks To Geeks.

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


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.ast.ASTFieldDeclaration;
9 import net.sourceforge.pmd.ast.ASTMethodDeclaration;
10
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13
14 public class AvoidFieldNameMatchingMethodName extends AbstractRule {
15
16     public Object JavaDoc visit(ASTClassOrInterfaceDeclaration node, Object JavaDoc data) {
17         if (node.isInterface()) {
18             return data;
19         }
20         return super.visit(node, data);
21     }
22
23     public Object JavaDoc visit(ASTFieldDeclaration node, Object JavaDoc data) {
24         String JavaDoc varName = node.getVariableName();
25         String JavaDoc fieldDeclaringType = getDeclaringType(node);
26         if (varName != null) {
27             varName = varName.toLowerCase();
28             ASTClassOrInterfaceDeclaration cl = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
29             if (cl != null) {
30                 List JavaDoc methods = cl.findChildrenOfType(ASTMethodDeclaration.class);
31                 for (Iterator JavaDoc it = methods.iterator(); it.hasNext();) {
32                     ASTMethodDeclaration m = (ASTMethodDeclaration) it.next();
33                     //Make sure we are comparing fields and methods inside same type
34
if (fieldDeclaringType.equals(getDeclaringType(m))) {
35                         String JavaDoc n = m.getMethodName();
36                         if (varName.equals(n.toLowerCase())) {
37                             addViolation(data, node);
38                         }
39                     }
40                 }
41             }
42         }
43         return data;
44     }
45 }
46
Popular Tags