View Javadoc

    1   package net.sourceforge.pmd.rules.imports;
    2
    3   import net.sourceforge.pmd.AbstractRule;
    4   import net.sourceforge.pmd.ast.ASTImportDeclaration;
    5   import net.sourceforge.pmd.ast.SimpleNode;
    6
    7   import java.util.Arrays;
    8   import java.util.HashSet;
    9   import java.util.Set;
    10
    11  public class DontImportJavaLang extends AbstractRule {
    12
    13      private Set<Package> skipPackages = new HashSet<Package>(Arrays.asList(new Package[] { Package.getPackage("java.lang.ref"), Package.getPackage("java.lang.reflect"), Package.getPackage("java.lang.annotation"),
    14              Package.getPackage("java.lang.instrument"), Package.getPackage("java.lang.management"), Package.getPackage("java.lang.Thread") }));
    15
    16      private Package javaLangPackage = Package.getPackage("java.lang");
    17
    18      public Object visit(ASTImportDeclaration node, Object data) {
    19
    20          if (node.isStatic()) {
    21              return data;
    22          }
    23
    24          if (node.getPackage() != null) {
    25              if(node.getPackage().equals(javaLangPackage) && !skipPackages.contains(node.getPackage())){
    26                  addViolation(data, node);
    27              }
    28          } else {
    29              String img = ((SimpleNode) node.jjtGetChild(0)).getImage();
    30              if (img.startsWith("java.lang")) {
    31                  if (img.startsWith("java.lang.ref")
    32                          || img.startsWith("java.lang.reflect")
    33                          || img.startsWith("java.lang.annotation")
    34                          || img.startsWith("java.lang.instrument")
    35                          || img.startsWith("java.lang.management")
    36                          || img.startsWith("java.lang.Thread.")) {
    37                      return data;
    38                  }
    39                  addViolation(data, node);
    40              }
    41          }
    42          return data;
    43      }
    44  }