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 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   * <ul>
53   * <li>
54   * Property {@code excludes} - Control whether to allow for certain classes via
55   * a star notation to be excluded such as {@code java.lang.Math.*} or specific
56   * static members to be excluded like {@code java.lang.System.out} for a variable
57   * or {@code java.lang.Math.random} for a method. See notes section for details.
58   * Type is {@code java.lang.String[]}.
59   * Default value is {@code ""}.
60   * </li>
61   * </ul>
62   *
63   * <p>
64   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
65   * </p>
66   *
67   * <p>
68   * Violation Message Keys:
69   * </p>
70   * <ul>
71   * <li>
72   * {@code import.avoidStatic}
73   * </li>
74   * </ul>
75   *
76   * @since 5.0
77   */
78  @StatelessCheck
79  public class AvoidStaticImportCheck
80      extends AbstractCheck {
81  
82      /**
83       * A key is pointing to the warning message text in "messages.properties"
84       * file.
85       */
86      public static final String MSG_KEY = "import.avoidStatic";
87  
88      /**
89       * Control whether to allow for certain classes via a star notation to be
90       * excluded such as {@code java.lang.Math.*} or specific static members
91       * to be excluded like {@code java.lang.System.out} for a variable or
92       * {@code java.lang.Math.random} for a method. See notes section for details.
93       */
94      private String[] excludes = CommonUtil.EMPTY_STRING_ARRAY;
95  
96      @Override
97      public int[] getDefaultTokens() {
98          return getRequiredTokens();
99      }
100 
101     @Override
102     public int[] getAcceptableTokens() {
103         return getRequiredTokens();
104     }
105 
106     @Override
107     public int[] getRequiredTokens() {
108         return new int[] {TokenTypes.STATIC_IMPORT};
109     }
110 
111     /**
112      * Setter to control whether to allow for certain classes via a star notation
113      * to be excluded such as {@code java.lang.Math.*} or specific static members
114      * to be excluded like {@code java.lang.System.out} for a variable or
115      * {@code java.lang.Math.random} for a method. See notes section for details.
116      *
117      * @param excludes fully-qualified class names/specific
118      *     static members where static imports are ok
119      * @since 5.0
120      */
121     public void setExcludes(String... excludes) {
122         this.excludes = excludes.clone();
123     }
124 
125     @Override
126     public void visitToken(final DetailAST ast) {
127         final DetailAST startingDot =
128             ast.getFirstChild().getNextSibling();
129         final FullIdent name = FullIdent.createFullIdent(startingDot);
130 
131         final String nameText = name.getText();
132         if (!isExempt(nameText)) {
133             log(startingDot, MSG_KEY, nameText);
134         }
135     }
136 
137     /**
138      * Checks if a class or static member is exempt from known excludes.
139      *
140      * @param classOrStaticMember
141      *                the class or static member
142      * @return true if except false if not
143      */
144     private boolean isExempt(String classOrStaticMember) {
145         boolean exempt = false;
146 
147         for (String exclude : excludes) {
148             if (classOrStaticMember.equals(exclude)
149                     || isStarImportOfPackage(classOrStaticMember, exclude)) {
150                 exempt = true;
151                 break;
152             }
153         }
154         return exempt;
155     }
156 
157     /**
158      * Returns true if classOrStaticMember is a starred name of package,
159      *  not just member name.
160      *
161      * @param classOrStaticMember - full name of member
162      * @param exclude - current exclusion
163      * @return true if member in exclusion list
164      */
165     private static boolean isStarImportOfPackage(String classOrStaticMember, String exclude) {
166         boolean result = false;
167         if (exclude.endsWith(".*")) {
168             // this section allows explicit imports
169             // to be exempt when configured using
170             // a starred import
171             final String excludeMinusDotStar =
172                 exclude.substring(0, exclude.length() - 2);
173             if (classOrStaticMember.startsWith(excludeMinusDotStar)
174                     && !classOrStaticMember.equals(excludeMinusDotStar)) {
175                 final String member = classOrStaticMember.substring(
176                         excludeMinusDotStar.length() + 1);
177                 // if it contains a dot then it is not a member but a package
178                 if (member.indexOf('.') == -1) {
179                     result = true;
180                 }
181             }
182         }
183         return result;
184     }
185 
186 }