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