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.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.Listwould 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 isboolean. Default value istrue.
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
import.unused
- 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 static final PatternRegex to match argument names.private static final PatternRegex to match class names.private booleanFlag to indicate when time to start collecting references.private UnusedImportsCheck.FrameThe scope is being processed.private static final PatternRegex to match the first class name.Set of the imports.private static final PatternRegexp pattern to match java.lang package.private static final PatternMethod pattern.static final StringA key is pointing to the warning message text in "messages.properties" file.private booleanControl whether to process Javadoc comments.private static final PatternReference pattern.private static final StringSuffix for the star import. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidCalled before the starting to process a tree.static Optional<JavadocTag>Attempts to match a reference string against a predefined pattern and extracts valid reference.private voidCollects references made in Javadoc comments.collectReferencesFromJavadoc(TextBlock textBlock) Process a javadocTextBlockand return the set of classes referenced within.private static @org.checkerframework.checker.index.qual.IndexOrLow({"#1"}) intextractReferencePart(String input) Extracts the reference part from an input string while ensuring balanced parentheses.voidfinishTree(DetailAST rootAST) Called after finished processing a tree.int[]The configurable token set.int[]Returns the default token a check is interested in.int[]The tokens that this check must be registered for.private static List<JavadocTag>getTargetTags(TextBlock cmt, JavadocUtil.JavadocTagType javadocTagType) Returns the list of valid tags found in a javadocTextBlock.private static booleanisMatchingTagType(JavadocTag tag, JavadocUtil.JavadocTagType javadocTagType) Checks if a Javadoc tag matches the expected type based on its extraction format.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.matchPattern(String identifier, Pattern pattern) private voidprocessIdent(DetailAST ast) Collects references made by IDENT.private voidprocessImport(DetailAST ast) Collects the details of imports.Returns a list of references that found in a javadocJavadocTag.private voidCollects the details of static imports.voidsetProcessJavadoc(boolean value) Setter to control whether to process Javadoc comments.private static StringtopLevelType(String type) If the given type string contains "."voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, 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:
-
CLASS_NAME
Regex to match class names. -
FIRST_CLASS_NAME
Regex to match the first class name. -
ARGUMENT_NAME
Regex to match argument names. -
JAVA_LANG_PACKAGE_PATTERN
Regexp pattern to match java.lang package. -
REFERENCE
Reference pattern. -
METHOD
Method pattern. -
STAR_IMPORT_SUFFIX
Suffix for the star import.- See Also:
-
imports
Set of the imports. -
collect
Flag to indicate when time to start collecting references. -
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
-
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 classAbstractCheck- 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
-
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.- Specified by:
getDefaultTokensin classAbstractCheck- Returns:
- the default tokens
- See Also:
-
getRequiredTokens
Description copied from class:AbstractCheckThe tokens that this check must be registered for.- Specified by:
getRequiredTokensin classAbstractCheck- Returns:
- the token set this must be registered for.
- 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.- Specified by:
getAcceptableTokensin classAbstractCheck- Returns:
- the token set this check is designed for.
- See Also:
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- 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
-
collectReferencesFromJavadoc
Collects references made in Javadoc comments.- Parameters:
ast- node to inspect for Javadoc
-
collectReferencesFromJavadoc
Process a javadocTextBlockand return the set of classes referenced within.- Parameters:
textBlock- The javadoc block to parse- Returns:
- a set of classes referenced in the javadoc block
-
getTargetTags
private static List<JavadocTag> getTargetTags(TextBlock cmt, JavadocUtil.JavadocTagType javadocTagType) Returns the list of valid tags found in a javadocTextBlock. Filters tags based on whether they are inline or block tags, ensuring they match the correct format supported.- Parameters:
cmt- The javadoc block to parsejavadocTagType- The type of tags we're interested in- Returns:
- the list of tags
-
processJavadocTag
Returns a list of references that found in a javadocJavadocTag.- Parameters:
tag- The javadoc tag to parse- Returns:
- A list of references that found in this tag
-
matchPattern
- Parameters:
identifier- The String to match the pattern againstpattern- The Pattern used to extract the texts- Returns:
- A set of texts which matched the pattern
-
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
-
isMatchingTagType
Checks if a Javadoc tag matches the expected type based on its extraction format. This method checks if an inline tag is extracted as a block tag or vice versa. It ensures that block tags are correctly recognized as block tags and inline tags as inline tags during processing.- Parameters:
tag- The Javadoc tag to check.javadocTagType- The expected type of the tag (BLOCK or INLINE).- Returns:
trueif the tag matches the expected type, otherwisefalse.
-
bestTryToMatchReference
Attempts to match a reference string against a predefined pattern and extracts valid reference.- Parameters:
tag- the input tag to check- Returns:
- Optional of extracted references
-
extractReferencePart
private static @org.checkerframework.checker.index.qual.IndexOrLow({"#1"}) int extractReferencePart(String input) Extracts the reference part from an input string while ensuring balanced parentheses.- Parameters:
input- the input string- Returns:
- -1 if parentheses are unbalanced, 0 if no method is found, or the index of the first space outside parentheses.
-