Class UnusedImportsCheck
java.lang.Object
com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
com.puppycrawl.tools.checkstyle.api.AbstractCheck
com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck
com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck
- All Implemented Interfaces:
Configurable,Contextualizable
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.langpackage. For example importingjava.lang.String. - The class imported is from the same package.
- A static method is imported when used as method reference. In that case, only the type needs to be imported and that's enough to resolve the method.
-
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.Setwould be considered referenced with the Javadoc comment{@link Set}. The alternative to avoid introducing a compile-time dependency would be to write the Javadoc comment as{@link Set}.
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.)
-
Module import declarations are used. Checkstyle does not resolve modules and therefore cannot
determine which packages or types are brought into scope by an
import moduledeclaration. See limitations.
- Since:
- 3.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final classHolds the names of referenced types and names of declared inner types.Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate UnusedImportsCheck.FrameThe scope is being processed.Set of the imports.private static final PatternRegexp pattern to match java.lang package.static final StringA key is pointing to the warning message text in "messages.properties" file.private static final PatternPattern for a valid Java identifier (parameter name).private booleanControl whether to process Javadoc comments.private static final StringSuffix for the star import.private static final StringPrefix for wildcard extends bound.private static final StringPrefix for wildcard super bound.Fields inherited from class com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck
MSG_JAVADOC_PARSE_RULE_ERROR, MSG_KEY_UNCLOSED_HTML_TAG -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate voidRegisters all type names referenced in a type string.voidCalled before the starting to process a tree.private static intfindMatchingCloseAngle(String str, int openIndex) Finds the matching close angle bracket for the angle bracket at the given index.voidfinishTree(DetailAST rootAST) Called after finished processing a tree.int[]The configurable token set.int[]Returns the default javadoc token types a check is interested in.int[]Returns the default token a check is interested in.int[]The javadoc tokens that this check must be registered for.int[]The tokens that this check must be registered for.private static booleanChecks whether ast is a fully qualified identifier.private booleanisUnusedImport(String imprt) Checks whether an import is unused.voidleaveToken(DetailAST ast) Called after all the child nodes have been process.private voidProcesses a Javadoc throws or exception tag to record referenced type.private voidprocessIdent(DetailAST ast) Collects references made by IDENT.private voidprocessImport(DetailAST ast) Collects the details of imports.private voidProcesses a Javadoc parameter type tag to record referenced type.private voidProcesses a Javadoc reference to record referenced types.private voidCollects the details of static imports.voidsetProcessJavadoc(boolean value) Setter to control whether to process Javadoc comments.voidsetViolateExecutionOnNonTightHtml(boolean shouldReportViolation) Setter to control when to print violations if the Javadoc being examined by this check violates the tight html rules defined at Tight-HTML Rules.splitTypeArguments(String typeArgs) Splits a type argument string into individual type argument strings.private static StringstripTrailingGt(String type) Strips trailing>characters from a type string.private static StringStrips a trailing parameter name (e.g.private static StringstripTypeArguments(String type) Strips generic type arguments from a type string.private static StringtopLevelType(String type) If the given type string contains "."voidCalled to process a Javadoc token.voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck
acceptJavadocWithNonTightHtml, beginJavadocTree, destroy, finishJavadocTree, getAcceptableJavadocTokens, getBlockCommentAst, init, isCommentNodesRequired, leaveJavadocToken, setJavadocTokensMethods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, log, log, log, setFileContents, setTabWidth, setTokensMethods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityMethods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
JAVA_LANG_PACKAGE_PATTERN
Regexp pattern to match java.lang package. -
STAR_IMPORT_SUFFIX
Suffix for the star import.- See Also:
-
WILDCARD_EXTENDS_PREFIX
Prefix for wildcard extends bound.- See Also:
-
WILDCARD_SUPER_PREFIX
Prefix for wildcard super bound.- See Also:
-
PARAM_NAME_PATTERN
Pattern for a valid Java identifier (parameter name). -
imports
Set of the imports. -
processJavadoc
Control whether to process Javadoc comments. -
currentFrame
The scope is being processed. Types declared in a scope can shadow imported types.
-
-
Constructor Details
-
UnusedImportsCheck
public UnusedImportsCheck()
-
-
Method Details
-
setProcessJavadoc
Setter to control whether to process Javadoc comments.- Parameters:
value- Flag for processing Javadoc comments.- Since:
- 5.4
-
setViolateExecutionOnNonTightHtml
Setter to control when to print violations if the Javadoc being examined by this check violates the tight html rules defined at Tight-HTML Rules.- Overrides:
setViolateExecutionOnNonTightHtmlin classAbstractJavadocCheck- Parameters:
shouldReportViolation- value to which the field shall be set to- Since:
- 8.3
-
beginTree
Description copied from class:AbstractCheckCalled before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTreein classAbstractJavadocCheck- Parameters:
rootAST- the root of the tree
-
finishTree
Description copied from class:AbstractCheckCalled after finished processing a tree. Ideal place to report on information collected whilst processing a tree.- Overrides:
finishTreein classAbstractCheck- Parameters:
rootAST- the root of the tree
-
getRequiredJavadocTokens
Description copied from class:AbstractJavadocCheckThe javadoc tokens that this check must be registered for.- Overrides:
getRequiredJavadocTokensin classAbstractJavadocCheck- Returns:
- the javadoc token set this must be registered for.
- See Also:
-
getDefaultJavadocTokens
Description copied from class:AbstractJavadocCheckReturns the default javadoc token types a check is interested in.- Specified by:
getDefaultJavadocTokensin classAbstractJavadocCheck- Returns:
- the default javadoc token types
- See Also:
-
visitJavadocToken
Description copied from class:AbstractJavadocCheckCalled to process a Javadoc token.- Specified by:
visitJavadocTokenin classAbstractJavadocCheck- Parameters:
ast- the token to process
-
getDefaultTokens
Description copied from class:AbstractCheckReturns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Overrides:
getDefaultTokensin classAbstractJavadocCheck- Returns:
- the default tokens
- See Also:
-
getAcceptableTokens
Description copied from class:AbstractCheckThe 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.- Overrides:
getAcceptableTokensin classAbstractJavadocCheck- Returns:
- the token set this check is designed for.
- See Also:
-
getRequiredTokens
Description copied from class:AbstractCheckThe tokens that this check must be registered for.- Overrides:
getRequiredTokensin classAbstractJavadocCheck- Returns:
- the token set this must be registered for.
- See Also:
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractJavadocCheck- Parameters:
ast- the token to process
-
leaveToken
Description copied from class:AbstractCheckCalled after all the child nodes have been process.- Overrides:
leaveTokenin classAbstractCheck- Parameters:
ast- the token leaving
-
isUnusedImport
Checks whether an import is unused.- Parameters:
imprt- an import.- Returns:
- true if an import is unused.
-
processIdent
Collects references made by IDENT.- Parameters:
ast- the IDENT node to process
-
isQualifiedIdentifier
Checks whether ast is a fully qualified identifier.- Parameters:
ast- to check- Returns:
- true if given ast is a fully qualified identifier
-
processImport
Collects the details of imports.- Parameters:
ast- node containing the import details
-
processStaticImport
Collects the details of static imports.- Parameters:
ast- node containing the static import details
-
processReference
Processes a Javadoc reference to record referenced types.- Parameters:
ast- the Javadoc reference node
-
processParameterType
Processes a Javadoc parameter type tag to record referenced type.- Parameters:
ast- the Javadoc parameter type node
-
addReferencedTypesFromType
Registers all type names referenced in a type string. Handles generic type arguments, wildcard bounds, and array suffixes.- Parameters:
type- the type string to process
-
processException
Processes a Javadoc throws or exception tag to record referenced type.- Parameters:
ast- the Javadoc throws or exception node
-
topLevelType
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
-
stripTypeArguments
Strips generic type arguments from a type string.- Parameters:
type- A type string possibly containing type arguments- Returns:
- The type string with type arguments removed
-
stripTrailingGt
Strips trailing>characters from a type string. This handles tokenization artifacts where the closing angle bracket of an enclosing generic is attached to the last parameter type.- Parameters:
type- A type string possibly ending with>- Returns:
- The type string with trailing
>characters removed
-
stripTrailingParameterName
Strips a trailing parameter name (e.g. "outputTarget" in "Result outputTarget") from a type token when the Javadoc lexer merges the type and parameter name into a single PARAMETER_TYPE token.Only strips if the substring after the last space is a valid Java identifier, which is true for a parameter name but false for generic content such as
BigDecimal>inClass<? extends BigDecimal>.- Parameters:
type- the raw token text- Returns:
- the type portion with any trailing parameter name removed
-
findMatchingCloseAngle
Finds the matching close angle bracket for the angle bracket at the given index. Correctly handles nested angle brackets by tracking depth.- Parameters:
str- the string to search inopenIndex- the index of the opening angle bracket- Returns:
- the index of the matching close angle bracket, or -1 if not found
-
splitTypeArguments
Splits a type argument string into individual type argument strings. Comma handling is deferred to a follow-up issue that absorbs commas into PARAMETER_TYPE; currently commas are token boundaries so only one type argument ever appears here.- Parameters:
typeArgs- the type argument string (content between angle brackets)- Returns:
- the list of individual type argument strings
-