View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.rule.unusedcode;
5   
6   import net.sourceforge.pmd.lang.ast.Node;
7   import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
8   import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration;
9   import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
10  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
11  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
12  
13  public class UnusedModifierRule extends AbstractJavaRule {
14  
15      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
16          if (!node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
17              ASTClassOrInterfaceDeclaration parentClassInterface = node
18                      .getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
19              if (parentClassInterface != null && parentClassInterface.isInterface()) {
20                  addViolation(data, node, getMessage());
21              }
22          } else if (node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
23              ASTClassOrInterfaceDeclaration parentClassInterface = node
24                      .getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
25              ASTEnumDeclaration parentEnum = node.getFirstParentOfType(ASTEnumDeclaration.class);
26              if (parentClassInterface != null
27                      && (parentClassInterface.isInterface() || !parentClassInterface.isInterface() && node.isStatic())
28                      || parentEnum != null) {
29                  addViolation(data, node, getMessage());
30              }
31          }
32          return super.visit(node, data);
33      }
34  
35      public Object visit(ASTMethodDeclaration node, Object data) {
36          if (node.isSyntacticallyPublic() || node.isSyntacticallyAbstract()) {
37              check(node, data);
38          }
39          return super.visit(node, data);
40      }
41  
42      public Object visit(ASTFieldDeclaration node, Object data) {
43          if (node.isSyntacticallyPublic() || node.isSyntacticallyStatic() || node.isSyntacticallyFinal()) {
44              check(node, data);
45          }
46          return super.visit(node, data);
47      }
48  
49      private void check(Node fieldOrMethod, Object data) {
50          // third ancestor could be an AllocationExpression
51          // if this is a method in an anonymous inner class
52          Node parent = fieldOrMethod.jjtGetParent().jjtGetParent().jjtGetParent();
53          if (parent instanceof ASTClassOrInterfaceDeclaration && ((ASTClassOrInterfaceDeclaration) parent).isInterface()) {
54              addViolation(data, fieldOrMethod);
55          }
56      }
57  }