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 com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.FullIdent;
26  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
27  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
28  
29  /**
30   * <div>
31   * Checks that there are no static import statements.
32   * </div>
33   *
34   * <p>
35   * Rationale: Importing static members can lead to naming conflicts
36   * between class' members. It may lead to poor code readability since it
37   * may no longer be clear what class a member resides in (without looking
38   * at the import statement).
39   * </p>
40   *
41   * <p>
42   * Notes:
43   * If you exclude a starred import on a class this automatically excludes
44   * each member individually.
45   * </p>
46   *
47   * <p>
48   * For example: Excluding {@code java.lang.Math.*}. will allow the import
49   * of each static member in the Math class individually like
50   * {@code java.lang.Math.PI, java.lang.Math.cos, ...}.
51   * </p>
52   *
53   * @since 5.0
54   */
55  @StatelessCheck
56  public class AvoidStaticImportCheck
57      extends AbstractCheck {
58  
59      /**
60       * A key is pointing to the warning message text in "messages.properties"
61       * file.
62       */
63      public static final String MSG_KEY = "import.avoidStatic";
64  
65      /**
66       * Control whether to allow for certain classes via a star notation to be
67       * excluded such as {@code java.lang.Math.*} or specific static members
68       * to be excluded like {@code java.lang.System.out} for a variable or
69       * {@code java.lang.Math.random} for a method. See notes section for details.
70       */
71      private String[] excludes = CommonUtil.EMPTY_STRING_ARRAY;
72  
73      /**
74       * Creates a new {@code AvoidStaticImportCheck} instance.
75       */
76      public AvoidStaticImportCheck() {
77          // no code by default
78      }
79  
80      @Override
81      public int[] getDefaultTokens() {
82          return getRequiredTokens();
83      }
84  
85      @Override
86      public int[] getAcceptableTokens() {
87          return getRequiredTokens();
88      }
89  
90      @Override
91      public int[] getRequiredTokens() {
92          return new int[] {TokenTypes.STATIC_IMPORT};
93      }
94  
95      /**
96       * Setter to control whether to allow for certain classes via a star notation
97       * to be excluded such as {@code java.lang.Math.*} or specific static members
98       * to be excluded like {@code java.lang.System.out} for a variable or
99       * {@code java.lang.Math.random} for a method. See notes section for details.
100      *
101      * @param excludes fully-qualified class names/specific
102      *     static members where static imports are ok
103      * @since 5.0
104      */
105     public void setExcludes(String... excludes) {
106         this.excludes = excludes.clone();
107     }
108 
109     @Override
110     public void visitToken(final DetailAST ast) {
111         final DetailAST startingDot =
112             ast.getFirstChild().getNextSibling();
113         final FullIdent name = FullIdent.createFullIdent(startingDot);
114 
115         final String nameText = name.getText();
116         if (!isExempt(nameText)) {
117             log(startingDot, MSG_KEY, nameText);
118         }
119     }
120 
121     /**
122      * Checks if a class or static member is exempt from known excludes.
123      *
124      * @param classOrStaticMember
125      *                the class or static member
126      * @return true if except false if not
127      */
128     private boolean isExempt(String classOrStaticMember) {
129         boolean exempt = false;
130 
131         for (String exclude : excludes) {
132             if (classOrStaticMember.equals(exclude)
133                     || isStarImportOfPackage(classOrStaticMember, exclude)) {
134                 exempt = true;
135                 break;
136             }
137         }
138         return exempt;
139     }
140 
141     /**
142      * Returns true if classOrStaticMember is a starred name of package,
143      *  not just member name.
144      *
145      * @param classOrStaticMember - full name of member
146      * @param exclude - current exclusion
147      * @return true if member in exclusion list
148      */
149     private static boolean isStarImportOfPackage(String classOrStaticMember, String exclude) {
150         boolean result = false;
151         if (exclude.endsWith(".*")) {
152             // this section allows explicit imports
153             // to be exempt when configured using
154             // a starred import
155             final String excludeMinusDotStar =
156                 exclude.substring(0, exclude.length() - 2);
157             if (classOrStaticMember.startsWith(excludeMinusDotStar)
158                     && !classOrStaticMember.equals(excludeMinusDotStar)) {
159                 final String member = classOrStaticMember.substring(
160                         excludeMinusDotStar.length() + 1);
161                 // if it contains a dot then it is not a member but a package
162                 if (member.indexOf('.') == -1) {
163                     result = true;
164                 }
165             }
166         }
167         return result;
168     }
169 
170 }