001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018///////////////////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.imports;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.FullIdent;
026import com.puppycrawl.tools.checkstyle.api.TokenTypes;
027import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
028
029/**
030 * <div>
031 * Checks that there are no static import statements.
032 * </div>
033 *
034 * <p>
035 * Rationale: Importing static members can lead to naming conflicts
036 * between class' members. It may lead to poor code readability since it
037 * may no longer be clear what class a member resides in (without looking
038 * at the import statement).
039 * </p>
040 *
041 * <p>
042 * Notes:
043 * If you exclude a starred import on a class this automatically excludes
044 * each member individually.
045 * </p>
046 *
047 * <p>
048 * For example: Excluding {@code java.lang.Math.*}. will allow the import
049 * of each static member in the Math class individually like
050 * {@code java.lang.Math.PI, java.lang.Math.cos, ...}.
051 * </p>
052 *
053 * @since 5.0
054 */
055@StatelessCheck
056public class AvoidStaticImportCheck
057    extends AbstractCheck {
058
059    /**
060     * A key is pointing to the warning message text in "messages.properties"
061     * file.
062     */
063    public static final String MSG_KEY = "import.avoidStatic";
064
065    /**
066     * Control whether to allow for certain classes via a star notation to be
067     * excluded such as {@code java.lang.Math.*} or specific static members
068     * to be excluded like {@code java.lang.System.out} for a variable or
069     * {@code java.lang.Math.random} for a method. See notes section for details.
070     */
071    private String[] excludes = CommonUtil.EMPTY_STRING_ARRAY;
072
073    /**
074     * Creates a new {@code AvoidStaticImportCheck} instance.
075     */
076    public AvoidStaticImportCheck() {
077        // no code by default
078    }
079
080    @Override
081    public int[] getDefaultTokens() {
082        return getRequiredTokens();
083    }
084
085    @Override
086    public int[] getAcceptableTokens() {
087        return getRequiredTokens();
088    }
089
090    @Override
091    public int[] getRequiredTokens() {
092        return new int[] {TokenTypes.STATIC_IMPORT};
093    }
094
095    /**
096     * Setter to control whether to allow for certain classes via a star notation
097     * to be excluded such as {@code java.lang.Math.*} or specific static members
098     * to be excluded like {@code java.lang.System.out} for a variable or
099     * {@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}