View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 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 or a module
38   *   is imported 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 and module imports. */
72      private final Set<FullIdent> staticAndModuleImports = new HashSet<>();
73  
74      /** Name of package in file. */
75      private String pkgName;
76  
77      /**
78       * Creates a new {@code RedundantImportCheck} instance.
79       */
80      public RedundantImportCheck() {
81          // no code by default
82      }
83  
84      @Override
85      public void beginTree(DetailAST aRootAST) {
86          pkgName = null;
87          imports.clear();
88          staticAndModuleImports.clear();
89      }
90  
91      @Override
92      public int[] getDefaultTokens() {
93          return getRequiredTokens();
94      }
95  
96      @Override
97      public int[] getAcceptableTokens() {
98          return getRequiredTokens();
99      }
100 
101     @Override
102     public int[] getRequiredTokens() {
103         return new int[] {
104             TokenTypes.IMPORT,
105             TokenTypes.STATIC_IMPORT,
106             TokenTypes.PACKAGE_DEF,
107             TokenTypes.MODULE_IMPORT,
108         };
109     }
110 
111     @Override
112     public void visitToken(DetailAST ast) {
113         if (ast.getType() == TokenTypes.PACKAGE_DEF) {
114             pkgName = FullIdent.createFullIdent(
115                     ast.getLastChild().getPreviousSibling()).getText();
116         }
117         else if (ast.getType() == TokenTypes.IMPORT) {
118             final FullIdent imp = FullIdent.createFullIdentBelow(ast);
119             final String importText = imp.getText();
120             if (isFromPackage(importText, "java.lang")) {
121                 log(ast, MSG_LANG, importText);
122             }
123             // imports from unnamed package are not allowed,
124             // so we are checking SAME rule only for named packages
125             else if (pkgName != null && isFromPackage(importText, pkgName)) {
126                 log(ast, MSG_SAME, importText);
127             }
128             // Check for a duplicate import
129             imports.stream().filter(full -> importText.equals(full.getText()))
130                 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
131 
132             imports.add(imp);
133         }
134         else {
135             // Check for a duplicate static or module import
136             final DetailAST identNode = ast.getLastChild().getPreviousSibling();
137             final FullIdent importFullIdent = FullIdent.createFullIdent(identNode);
138             final String importText = importFullIdent.getText();
139 
140             staticAndModuleImports
141                     .stream()
142                     .filter(existingImport -> importText.equals(existingImport.getText()))
143                     .forEach(existingImport -> {
144                         log(ast, MSG_DUPLICATE, existingImport.getLineNo(), importText);
145                     });
146 
147             staticAndModuleImports.add(importFullIdent);
148         }
149     }
150 
151     /**
152      * Determines if an import statement is for types from a specified package.
153      *
154      * @param importName the import name
155      * @param pkg the package name
156      * @return whether from the package
157      */
158     private static boolean isFromPackage(String importName, String pkg) {
159         // imports from unnamed package are not allowed:
160         // https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5
161         // So '.' must be present in member name and we are not checking for it
162         final int index = importName.lastIndexOf('.');
163         final String front = importName.substring(0, index);
164         return pkg.equals(front);
165     }
166 
167 }