View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.imports;
21  
22  import java.util.HashSet;
23  import java.util.Set;
24  
25  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
26  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27  import com.puppycrawl.tools.checkstyle.api.DetailAST;
28  import com.puppycrawl.tools.checkstyle.api.FullIdent;
29  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30  
31  /**
32   * <div>
33   * Checks for redundant import statements. An import statement is
34   * considered redundant if:
35   * </div>
36   * <ul>
37   *   <li>It is a duplicate of another import. This is, when a class is imported
38   *   more than once.</li>
39   *   <li>The class non-statically imported is from the {@code java.lang}
40   *   package, e.g. importing {@code java.lang.String}.</li>
41   *   <li>The class non-statically imported is from the same package as the
42   *   current package.</li>
43   * </ul>
44   *
45   * @since 3.0
46   */
47  @FileStatefulCheck
48  public class RedundantImportCheck
49      extends AbstractCheck {
50  
51      /**
52       * A key is pointing to the warning message text in "messages.properties"
53       * file.
54       */
55      public static final String MSG_LANG = "import.lang";
56  
57      /**
58       * A key is pointing to the warning message text in "messages.properties"
59       * file.
60       */
61      public static final String MSG_SAME = "import.same";
62  
63      /**
64       * A key is pointing to the warning message text in "messages.properties"
65       * file.
66       */
67      public static final String MSG_DUPLICATE = "import.duplicate";
68  
69      /** Set of the imports. */
70      private final Set<FullIdent> imports = new HashSet<>();
71      /** Set of static imports. */
72      private final Set<FullIdent> staticImports = new HashSet<>();
73  
74      /** Name of package in file. */
75      private String pkgName;
76  
77      @Override
78      public void beginTree(DetailAST aRootAST) {
79          pkgName = null;
80          imports.clear();
81          staticImports.clear();
82      }
83  
84      @Override
85      public int[] getDefaultTokens() {
86          return getRequiredTokens();
87      }
88  
89      @Override
90      public int[] getAcceptableTokens() {
91          return getRequiredTokens();
92      }
93  
94      @Override
95      public int[] getRequiredTokens() {
96          return new int[] {
97              TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF,
98          };
99      }
100 
101     @Override
102     public void visitToken(DetailAST ast) {
103         if (ast.getType() == TokenTypes.PACKAGE_DEF) {
104             pkgName = FullIdent.createFullIdent(
105                     ast.getLastChild().getPreviousSibling()).getText();
106         }
107         else if (ast.getType() == TokenTypes.IMPORT) {
108             final FullIdent imp = FullIdent.createFullIdentBelow(ast);
109             final String importText = imp.getText();
110             if (isFromPackage(importText, "java.lang")) {
111                 log(ast, MSG_LANG, importText);
112             }
113             // imports from unnamed package are not allowed,
114             // so we are checking SAME rule only for named packages
115             else if (pkgName != null && isFromPackage(importText, pkgName)) {
116                 log(ast, MSG_SAME, importText);
117             }
118             // Check for a duplicate import
119             imports.stream().filter(full -> importText.equals(full.getText()))
120                 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
121 
122             imports.add(imp);
123         }
124         else {
125             // Check for a duplicate static import
126             final FullIdent imp =
127                 FullIdent.createFullIdent(
128                     ast.getLastChild().getPreviousSibling());
129             staticImports.stream().filter(full -> imp.getText().equals(full.getText()))
130                 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), imp.getText()));
131 
132             staticImports.add(imp);
133         }
134     }
135 
136     /**
137      * Determines if an import statement is for types from a specified package.
138      *
139      * @param importName the import name
140      * @param pkg the package name
141      * @return whether from the package
142      */
143     private static boolean isFromPackage(String importName, String pkg) {
144         // imports from unnamed package are not allowed:
145         // https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5
146         // So '.' must be present in member name and we are not checking for it
147         final int index = importName.lastIndexOf('.');
148         final String front = importName.substring(0, index);
149         return pkg.equals(front);
150     }
151 
152 }