Class UnusedImportsCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class UnusedImportsCheck
    extends AbstractCheck

    Checks for unused import statements. An import statement is considered unused if:

    • It is not referenced in the file. The algorithm does not support wild-card imports like import java.io.*;. Most IDE's provide very sophisticated checks for imports that handle wild-card imports.
    • The class imported is from the java.lang package. For example importing java.lang.String.
    • The class imported is from the same package.
    • Optionally: it is referenced in Javadoc comments. This check is on by default, but it is considered bad practice to introduce a compile-time dependency for documentation purposes only. As an example, the import java.util.List would be considered referenced with the Javadoc comment {@link List}. The alternative to avoid introducing a compile-time dependency would be to write the Javadoc comment as {@link java.util.List}.

    The main limitation of this check is handling the cases where:

    • An imported type has the same name as a declaration, such as a member variable.
    • There are two or more static imports with the same method name (javac can distinguish imports with same name but different parameters, but checkstyle can not due to limitation.)
    • Property processJavadoc - Control whether to process Javadoc comments. Type is boolean. Default value is true.

    To configure the check:

     <module name="UnusedImports"/>
     

    Example:

     // limitation as it match field name in code
     import java.awt.Component; //OK
    
     // no ability to recognize what import is not used
     import static java.util.Map.copyOf; //OK
     import static java.util.Arrays.copyOf; //OK
    
     import java.lang.String; // violation
    
     import java.util.Stack;  // OK
     import java.util.Map;   // violation
    
     import java.util.List; // OK
    
     /**
      * @link List
     */
     class MyClass{
       Stack stack = new Stack();
       private Object Component;
       int[] arr = {0,0};
       int[] array = copyOf(arr , 1);
     }
     

    To configure the check so that it ignores the imports referenced in Javadoc comments:

     <module name="UnusedImports">
       <property name="processJavadoc" value="false"/>
     </module>
     

    Example:

     // limitation as it match field name in code
     import java.awt.Component; //OK
    
     // no ability to recognize what import is not used
     import static java.util.Map.copyOf; //OK
     import static java.util.Arrays.copyOf; //OK
    
     import java.lang.String; // violation
    
     import java.util.Stack;  // OK
     import java.util.Map;   // violation
    
     import java.util.List; // violation
    
     /**
      * @link List
     */
     class MyClass{
       Stack stack = new Stack();
       private Object Component;
       int[] arr = {0,0};
       int[] array = copyOf(arr , 1);
     }
     

    Parent is com.puppycrawl.tools.checkstyle.TreeWalker

    Violation Message Keys:

    • import.unused
    Since:
    3.0
    • Field Detail

      • MSG_KEY

        public static final java.lang.String MSG_KEY
        A key is pointing to the warning message text in "messages.properties" file.
        See Also:
        Constant Field Values
      • CLASS_NAME

        private static final java.util.regex.Pattern CLASS_NAME
        Regex to match class names.
      • FIRST_CLASS_NAME

        private static final java.util.regex.Pattern FIRST_CLASS_NAME
        Regex to match the first class name.
      • ARGUMENT_NAME

        private static final java.util.regex.Pattern ARGUMENT_NAME
        Regex to match argument names.
      • JAVA_LANG_PACKAGE_PATTERN

        private static final java.util.regex.Pattern JAVA_LANG_PACKAGE_PATTERN
        Regexp pattern to match java.lang package.
      • collect

        private boolean collect
        Flag to indicate when time to start collecting references.
      • processJavadoc

        private boolean processJavadoc
        Control whether to process Javadoc comments.
    • Method Detail

      • setProcessJavadoc

        public void setProcessJavadoc​(boolean value)
        Setter to control whether to process Javadoc comments.
        Parameters:
        value - Flag for processing Javadoc comments.
      • beginTree

        public void beginTree​(DetailAST rootAST)
        Description copied from class: AbstractCheck
        Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.
        Overrides:
        beginTree in class AbstractCheck
        Parameters:
        rootAST - the root of the tree
      • finishTree

        public void finishTree​(DetailAST rootAST)
        Description copied from class: AbstractCheck
        Called after finished processing a tree. Ideal place to report on information collected whilst processing a tree.
        Overrides:
        finishTree in class AbstractCheck
        Parameters:
        rootAST - the root of the tree
      • getAcceptableTokens

        public int[] getAcceptableTokens()
        Description copied from class: AbstractCheck
        The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.
        Specified by:
        getAcceptableTokens in class AbstractCheck
        Returns:
        the token set this check is designed for.
        See Also:
        TokenTypes
      • isUnusedImport

        private boolean isUnusedImport​(java.lang.String imprt)
        Checks whether an import is unused.
        Parameters:
        imprt - an import.
        Returns:
        true if an import is unused.
      • processIdent

        private void processIdent​(DetailAST ast)
        Collects references made by IDENT.
        Parameters:
        ast - the IDENT node to process
      • processImport

        private void processImport​(DetailAST ast)
        Collects the details of imports.
        Parameters:
        ast - node containing the import details
      • processStaticImport

        private void processStaticImport​(DetailAST ast)
        Collects the details of static imports.
        Parameters:
        ast - node containing the static import details
      • collectReferencesFromJavadoc

        private void collectReferencesFromJavadoc​(DetailAST ast)
        Collects references made in Javadoc comments.
        Parameters:
        ast - node to inspect for Javadoc
      • collectReferencesFromJavadoc

        private static java.util.Set<java.lang.String> collectReferencesFromJavadoc​(TextBlock textBlock)
        Process a javadoc TextBlock and return the set of classes referenced within.
        Parameters:
        textBlock - The javadoc block to parse
        Returns:
        a set of classes referenced in the javadoc block
      • processJavadocTag

        private static java.util.Set<java.lang.String> processJavadocTag​(JavadocTag tag)
        Returns a list of references that found in a javadoc JavadocTag.
        Parameters:
        tag - The javadoc tag to parse
        Returns:
        A list of references that found in this tag
      • matchPattern

        private static java.util.Set<java.lang.String> matchPattern​(java.lang.String identifier,
                                                                    java.util.regex.Pattern pattern)
        Extracts a set of texts matching a Pattern from a String.
        Parameters:
        identifier - The String to match the pattern against
        pattern - The Pattern used to extract the texts
        Returns:
        A set of texts which matched the pattern
      • topLevelType

        private static java.lang.String topLevelType​(java.lang.String type)
        If the given type string contains "." (e.g. "Map.Entry"), returns the top level type (e.g. "Map"), as that is what must be imported for the type to resolve. Otherwise, returns the type as-is.
        Parameters:
        type - A possibly qualified type name
        Returns:
        The simple name of the top level type