View Javadoc

    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;
    12  import java.util.List;
    13  import java.util.Map;
    14
    15  public class UnusedPrivateFieldRule extends AbstractRule {
    16
    17      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    18          Map vars = node.getScope().getVariableDeclarations();
    19          for (Iterator i = vars.keySet().iterator(); i.hasNext();) {
    20              VariableNameDeclaration decl = (VariableNameDeclaration) i.next();
    21              if (!decl.getAccessNodeParent().isPrivate() || isOK(decl.getImage())) {
    22                  continue;
    23              }
    24              if (!actuallyUsed((List) vars.get(decl))) {
    25                  addViolation(data, decl.getNode(), decl.getImage());
    26              }
    27          }
    28          return super.visit(node, data);
    29      }
    30
    31      private boolean actuallyUsed(List usages) {
    32          for (Iterator j = usages.iterator(); j.hasNext();) {
    33              NameOccurrence nameOccurrence = (NameOccurrence) j.next();
    34              if (!nameOccurrence.isOnLeftHandSide()) {
    35                  return true;
    36              }
    37          }
    38          return false;
    39      }
    40
    41      private boolean isOK(String image) {
    42          return image.equals("serialVersionUID") || image.equals("serialPersistentFields") || image.equals("IDENT");
    43      }
    44  }