Class UnusedPrivateFieldCheck
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.coding.UnusedPrivateFieldCheck
- All Implemented Interfaces:
Configurable,Contextualizable
Check that a private field is declared, but never used. Fields with any other
visibility (package-private, protected, or public), including those declared in
an implicitly declared class (compact source file), are not checked.
- Since:
- 14.1.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final recordA recorded, not-yet-resolved reference to a field name, with enough context to resolve it precisely once the whole file has been visited.private static final recordHolds a private field entry, reported if never resolved to by any usage.private static final recordA recorded field-name access on a qualifier whose declared type is known precisely.Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions -
Field Summary
FieldsModifier and TypeFieldDescriptionStack of currently open enclosing type names.private final List<UnusedPrivateFieldCheck.FieldUsage> Recorded field-name usage occurrences.Global set of field names accessed.Specify annotations canonical names which ignore variables in consideration.Set of ignore annotations short names.private PatternSpecify a regular expression pattern for field names to ignore.static final StringA key is pointing to the warning message text in "messages.properties".private final List<UnusedPrivateFieldCheck.PendingField> Accumulated pending fields, reported at finishTree.Stack of private field maps, one per class nesting level.Each class's private fields, keyed by simple type name, populated once a class's OBJBLOCK closes.Scope stack tracking local variable and parameter names per block.Snapshots of scope stack saved when entering a nested class, restored when leaving it.private final List<UnusedPrivateFieldCheck.TypedUsage> Recorded field-name accesses on a qualifier. -
Constructor Summary
ConstructorsConstructorDescriptionCreates a newUnusedPrivateFieldCheckinstance with default values. -
Method Summary
Modifier and TypeMethodDescriptionvoidCalled before the starting to process a tree.private StringfindDeclaredType(String name) Looks up the declared simple type name of a local variable or parameter currently in scope.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 voidhandleDotAccess(DetailAST dot, String name) Classifies a dot-qualified reference:this.fieldandClassName.this.fieldare resolved precisely; any other qualifier (an arbitrary object or type reference) cannot be resolved without type information, so it falls back to name-only matching viaglobalUsedFields.private voidhandleIdent(DetailAST ast) Records field usage, respecting local variable and parameter shadowing.private voidCollects private field declarations.private booleanhasIgnoredAnnotation(DetailAST variableDef) Checks whether a field should be ignored because either the field itself or its enclosing type (class, interface, enum, or record) carries an annotation present inignoreAnnotationCanonicalNames(matched by canonical or short name).private booleanChecks whether the given AST node (a field or a type definition) carries an annotation present inignoreAnnotationCanonicalNames, matched either by canonical name or by short name.private static booleanisDeclarationParent(DetailAST parent) Checks whether the given parent node is a declaration site whose IDENT child names the declared element itself (a variable, method, constructor, or type), rather than referencing some other field.private static booleanChecks whether a field is private.voidleaveToken(DetailAST ast) Called after all the child nodes have been process.private voidrecordUsage(String name, String qualifierTypeName, boolean bareThisQualified) Snapshots the currently open class chain (field maps and type names) so the usage can be resolved later, once every class in the file is fully populated.private static StringresolveDeclaredTypeName(DetailAST varOrParamDef) Extracts the declared simple type name of a VARIABLE_DEF or PARAMETER_DEF, if determinable.private static DetailASTResolves a recorded usage to the exact field declaration it refers to, following the same shadowing rules Java itself applies.voidsetIgnoreAnnotationCanonicalNames(String... annotationNames) Setter to specify annotations canonical names which ignore variables in consideration.voidsetIgnoredFieldPattern(Pattern pattern) Setter to specify a regular expression pattern for field names to ignore, even if they otherwise satisfy this check's detection of an unused private field.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_PRIVATE_FIELD
A key is pointing to the warning message text in "messages.properties".- See Also:
-
privateFields
Stack of private field maps, one per class nesting level. -
enclosingTypeNames
Stack of currently open enclosing type names. -
fieldUsages
Recorded field-name usage occurrences. -
globalUsedFields
Global set of field names accessed. -
pendingFields
Accumulated pending fields, reported at finishTree. -
scopeStack
Scope stack tracking local variable and parameter names per block. -
scopeStackSnapshots
Snapshots of scope stack saved when entering a nested class, restored when leaving it. -
typedUsages
Recorded field-name accesses on a qualifier. -
privateFieldsByType
Each class's private fields, keyed by simple type name, populated once a class's OBJBLOCK closes. Used to resolvetypedUsages. -
ignoreAnnotationCanonicalNames
Specify annotations canonical names which ignore variables in consideration. A field is ignored either when the field itself carries a matching annotation, or when its enclosing class, interface, enum, or record carries one (e.g. a class-level Lombok@Getter). -
ignoredFieldPattern
Specify a regular expression pattern for field names to ignore. -
ignoreAnnotationShortNames
Set of ignore annotations short names.
-
-
Constructor Details
-
UnusedPrivateFieldCheck
public UnusedPrivateFieldCheck()Creates a newUnusedPrivateFieldCheckinstance with default values.
-
-
Method Details
-
setIgnoreAnnotationCanonicalNames
Setter to specify annotations canonical names which ignore variables in consideration.- Parameters:
annotationNames- array of ignore annotations canonical names.- Since:
- 14.1.0
-
setIgnoredFieldPattern
Setter to specify a regular expression pattern for field names to ignore, even if they otherwise satisfy this check's detection of an unused private field. Note this replaces the default value entirely — to keepserialVersionUIDignored alongside your own pattern, include it explicitly, e.g.^(serialVersionUID|LOG|LOGGER)$.- Parameters:
pattern- regular expression pattern for field names to ignore.- Since:
- 14.1.0
-
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:
-
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:
-
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
-
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
-
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
-
resolveUsage
Resolves a recorded usage to the exact field declaration it refers to, following the same shadowing rules Java itself applies.- Parameters:
usage- the recorded usage to resolve.- Returns:
- the DetailAST of the field it resolves to, or null if none.
-
handleVariableDef
Collects private field declarations.- Parameters:
ast- for this method.
-
hasIgnoredAnnotation
Checks whether a field should be ignored because either the field itself or its enclosing type (class, interface, enum, or record) carries an annotation present inignoreAnnotationCanonicalNames(matched by canonical or short name).- Parameters:
variableDef- the VARIABLE_DEF node.- Returns:
- true if the field or its enclosing type has a matching ignore annotation.
-
isAnnotatedWithIgnoredAnnotation
Checks whether the given AST node (a field or a type definition) carries an annotation present inignoreAnnotationCanonicalNames, matched either by canonical name or by short name.- Parameters:
ast- the VARIABLE_DEF, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, RECORD_DEF, or ANNOTATION_DEF node to inspect.- Returns:
- true if a matching ignore annotation is present directly on
ast.
-
handleIdent
Records field usage, respecting local variable and parameter shadowing. Resolution to a specific field declaration happens later, atfinishTree(com.puppycrawl.tools.checkstyle.api.DetailAST).- Parameters:
ast- for handleIdent
-
handleDotAccess
Classifies a dot-qualified reference:this.fieldandClassName.this.fieldare resolved precisely; any other qualifier (an arbitrary object or type reference) cannot be resolved without type information, so it falls back to name-only matching viaglobalUsedFields.- Parameters:
dot- the DOT node whose last child is the field IDENT.name- the field name being accessed.
-
findDeclaredType
Looks up the declared simple type name of a local variable or parameter currently in scope.- Parameters:
name- the variable or parameter name.- Returns:
- its declared simple type name, or null if the name is not a tracked local/parameter, or its type could not be determined.
-
resolveDeclaredTypeName
Extracts the declared simple type name of a VARIABLE_DEF or PARAMETER_DEF, if determinable.- Parameters:
varOrParamDef- the VARIABLE_DEF or PARAMETER_DEF node.- Returns:
- the simple type name, or null if it could not be determined (e.g. primitive types, inferred/generic-only forms).
-
recordUsage
Snapshots the currently open class chain (field maps and type names) so the usage can be resolved later, once every class in the file is fully populated.- Parameters:
name- the field name referenced.qualifierTypeName- the enclosing type name named in aClassName.this.fieldreference, or null.bareThisQualified- true for athis.fieldreference.
-
isDeclarationParent
Checks whether the given parent node is a declaration site whose IDENT child names the declared element itself (a variable, method, constructor, or type), rather than referencing some other field.- Parameters:
parent- the parent of the IDENT being inspected.- Returns:
- true if the IDENT is a declaration name, not a usage.
-
isPrivate
Checks whether a field is private.- Parameters:
modifiers- for isPrivate method.- Returns:
- modifiers of literal_private.
-