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 that there are no import statements that use the {@code *} notation.
34   * </div>
35   *
36   * <p>
37   * Rationale: Importing all classes from a package or static
38   * members from a class leads to tight coupling between packages
39   * or classes and might lead to problems when a new version of a
40   * library introduces name clashes.
41   * </p>
42   *
43   * <p>
44   * Notes:
45   * Note that property {@code excludes} is not recursive, subpackages of excluded
46   * packages are not automatically excluded.
47   * </p>
48   *
49   * @since 3.0
50   */
51  @FileStatefulCheck
52  public class AvoidStarImportCheck
53      extends AbstractCheck {
54  
55      /**
56       * A key is pointing to the warning message text in "messages.properties"
57       * file.
58       */
59      public static final String MSG_KEY = "import.avoidStar";
60  
61      /**
62       * A key is pointing to the warning message text in "messages.properties"
63       * file.
64       */
65      public static final String MSG_COUNT = "import.avoidStarCount";
66  
67      /** Suffix for the star import. */
68      private static final String STAR_IMPORT_SUFFIX = ".*";
69  
70      /**
71       * Specify packages where starred class imports are
72       * allowed and classes where starred static member imports are allowed.
73       */
74      private final Set<String> excludes = new HashSet<>();
75  
76      /**
77       * Control whether to allow starred class imports like
78       * {@code import java.util.*;}.
79       */
80      private boolean allowClassImports;
81  
82      /**
83       * Control whether to allow starred static member imports like
84       * {@code import static org.junit.Assert.*;}.
85       */
86      private boolean allowStaticMemberImports;
87  
88      /**
89       * Maximum number of allowed star imports.
90       */
91      private int maxAllowedStarImports;
92  
93      /**
94       * Counter for used star imports.
95       */
96      private int currentStarImportsCount;
97  
98      /**
99       * Creates a new {@code AvoidStarImportCheck} instance.
100      */
101     public AvoidStarImportCheck() {
102         // no code by default
103     }
104 
105     @Override
106     public int[] getDefaultTokens() {
107         return getRequiredTokens();
108     }
109 
110     @Override
111     public int[] getAcceptableTokens() {
112         return getRequiredTokens();
113     }
114 
115     @Override
116     public int[] getRequiredTokens() {
117         // original implementation checks both IMPORT and STATIC_IMPORT tokens to avoid ".*" imports
118         // however user can allow using "import" or "import static"
119         // by configuring allowClassImports and allowStaticMemberImports
120         // To avoid potential confusion when user specifies conflicting options on configuration
121         // (see example below) we are adding both tokens to Required list
122         //   <module name="AvoidStarImport">
123         //      <property name="tokens" value="IMPORT"/>
124         //      <property name="allowStaticMemberImports" value="false"/>
125         //   </module>
126         return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT};
127     }
128 
129     /**
130      * Setter to specify packages where starred class imports are
131      * allowed and classes where starred static member imports are allowed.
132      *
133      * @param excludesParam package names/fully-qualifies class names
134      *     where star imports are ok
135      * @since 3.2
136      */
137     public void setExcludes(String... excludesParam) {
138         for (final String exclude : excludesParam) {
139             if (exclude.endsWith(STAR_IMPORT_SUFFIX)) {
140                 excludes.add(exclude);
141             }
142             else {
143                 excludes.add(exclude + STAR_IMPORT_SUFFIX);
144             }
145         }
146     }
147 
148     /**
149      * Setter to control whether to allow starred class imports like
150      * {@code import java.util.*;}.
151      *
152      * @param allow true to allow false to disallow
153      * @since 5.3
154      */
155     public void setAllowClassImports(boolean allow) {
156         allowClassImports = allow;
157     }
158 
159     /**
160      * Setter to control whether to allow starred static member imports like
161      * {@code import static org.junit.Assert.*;}.
162      *
163      * @param allow true to allow false to disallow
164      * @since 5.3
165      */
166     public void setAllowStaticMemberImports(boolean allow) {
167         allowStaticMemberImports = allow;
168     }
169 
170     /**
171      * Setter to control how many star imports are allowed.
172      *
173      * @param count the number of star imports allowed
174      * @since 13.5.0
175      */
176     public void setMaxAllowedStarImports(int count) {
177         maxAllowedStarImports = count;
178     }
179 
180     @Override
181     public void beginTree(DetailAST rootAST) {
182         currentStarImportsCount = 0;
183     }
184 
185     @Override
186     public void visitToken(final DetailAST ast) {
187         if (ast.getType() == TokenTypes.IMPORT) {
188             if (!allowClassImports) {
189                 final DetailAST startingDot = ast.getFirstChild();
190                 logsStarredImportViolation(startingDot);
191             }
192         }
193         else if (!allowStaticMemberImports) {
194             // must navigate past the static keyword
195             final DetailAST startingDot = ast.getFirstChild().getNextSibling();
196             logsStarredImportViolation(startingDot);
197         }
198     }
199 
200     /**
201      * Gets the full import identifier.  If the import is a starred import and
202      * it's not excluded then a violation is logged.
203      *
204      * @param startingDot the starting dot for the import statement
205      */
206     private void logsStarredImportViolation(DetailAST startingDot) {
207         final FullIdent name = FullIdent.createFullIdent(startingDot);
208         final String importText = name.getText();
209         final boolean isStarImport = importText.endsWith(STAR_IMPORT_SUFFIX);
210         if (isStarImport) {
211             currentStarImportsCount++;
212             if (currentStarImportsCount > maxAllowedStarImports
213                     && !excludes.contains(importText)) {
214                 if (maxAllowedStarImports > 0) {
215                     log(startingDot, MSG_COUNT, maxAllowedStarImports);
216                 }
217                 else {
218                     log(startingDot, MSG_KEY, importText);
219                 }
220             }
221         }
222     }
223 
224 }