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.StatelessCheck;
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  @StatelessCheck
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      /** Suffix for the star import. */
62      private static final String STAR_IMPORT_SUFFIX = ".*";
63  
64      /**
65       * Specify packages where starred class imports are
66       * allowed and classes where starred static member imports are allowed.
67       */
68      private final Set<String> excludes = new HashSet<>();
69  
70      /**
71       * Control whether to allow starred class imports like
72       * {@code import java.util.*;}.
73       */
74      private boolean allowClassImports;
75  
76      /**
77       * Control whether to allow starred static member imports like
78       * {@code import static org.junit.Assert.*;}.
79       */
80      private boolean allowStaticMemberImports;
81  
82      @Override
83      public int[] getDefaultTokens() {
84          return getRequiredTokens();
85      }
86  
87      @Override
88      public int[] getAcceptableTokens() {
89          return getRequiredTokens();
90      }
91  
92      @Override
93      public int[] getRequiredTokens() {
94          // original implementation checks both IMPORT and STATIC_IMPORT tokens to avoid ".*" imports
95          // however user can allow using "import" or "import static"
96          // by configuring allowClassImports and allowStaticMemberImports
97          // To avoid potential confusion when user specifies conflicting options on configuration
98          // (see example below) we are adding both tokens to Required list
99          //   <module name="AvoidStarImport">
100         //      <property name="tokens" value="IMPORT"/>
101         //      <property name="allowStaticMemberImports" value="false"/>
102         //   </module>
103         return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT};
104     }
105 
106     /**
107      * Setter to specify packages where starred class imports are
108      * allowed and classes where starred static member imports are allowed.
109      *
110      * @param excludesParam package names/fully-qualifies class names
111      *     where star imports are ok
112      * @since 3.2
113      */
114     public void setExcludes(String... excludesParam) {
115         for (final String exclude : excludesParam) {
116             if (exclude.endsWith(STAR_IMPORT_SUFFIX)) {
117                 excludes.add(exclude);
118             }
119             else {
120                 excludes.add(exclude + STAR_IMPORT_SUFFIX);
121             }
122         }
123     }
124 
125     /**
126      * Setter to control whether to allow starred class imports like
127      * {@code import java.util.*;}.
128      *
129      * @param allow true to allow false to disallow
130      * @since 5.3
131      */
132     public void setAllowClassImports(boolean allow) {
133         allowClassImports = allow;
134     }
135 
136     /**
137      * Setter to control whether to allow starred static member imports like
138      * {@code import static org.junit.Assert.*;}.
139      *
140      * @param allow true to allow false to disallow
141      * @since 5.3
142      */
143     public void setAllowStaticMemberImports(boolean allow) {
144         allowStaticMemberImports = allow;
145     }
146 
147     @Override
148     public void visitToken(final DetailAST ast) {
149         if (ast.getType() == TokenTypes.IMPORT) {
150             if (!allowClassImports) {
151                 final DetailAST startingDot = ast.getFirstChild();
152                 logsStarredImportViolation(startingDot);
153             }
154         }
155         else if (!allowStaticMemberImports) {
156             // must navigate past the static keyword
157             final DetailAST startingDot = ast.getFirstChild().getNextSibling();
158             logsStarredImportViolation(startingDot);
159         }
160     }
161 
162     /**
163      * Gets the full import identifier.  If the import is a starred import and
164      * it's not excluded then a violation is logged.
165      *
166      * @param startingDot the starting dot for the import statement
167      */
168     private void logsStarredImportViolation(DetailAST startingDot) {
169         final FullIdent name = FullIdent.createFullIdent(startingDot);
170         final String importText = name.getText();
171         if (importText.endsWith(STAR_IMPORT_SUFFIX) && !excludes.contains(importText)) {
172             log(startingDot, MSG_KEY, importText);
173         }
174     }
175 
176 }