All Implemented Interfaces:
Configurable, Contextualizable

public class UnusedPrivateFieldCheck extends AbstractCheck
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
  • Field Details

    • MSG_PRIVATE_FIELD

      public static final String MSG_PRIVATE_FIELD
      A key is pointing to the warning message text in "messages.properties".
      See Also:
    • privateFields

      private final Deque<Map<String,DetailAST>> privateFields
      Stack of private field maps, one per class nesting level.
    • enclosingTypeNames

      private final Deque<String> enclosingTypeNames
      Stack of currently open enclosing type names.
    • fieldUsages

      private final List<UnusedPrivateFieldCheck.FieldUsage> fieldUsages
      Recorded field-name usage occurrences.
    • globalUsedFields

      private final Set<String> globalUsedFields
      Global set of field names accessed.
    • pendingFields

      private final List<UnusedPrivateFieldCheck.PendingField> pendingFields
      Accumulated pending fields, reported at finishTree.
    • scopeStack

      private final Deque<Map<String,String>> scopeStack
      Scope stack tracking local variable and parameter names per block.
    • scopeStackSnapshots

      private final Deque<Deque<Map<String,String>>> scopeStackSnapshots
      Snapshots of scope stack saved when entering a nested class, restored when leaving it.
    • typedUsages

      private final List<UnusedPrivateFieldCheck.TypedUsage> typedUsages
      Recorded field-name accesses on a qualifier.
    • privateFieldsByType

      private final Map<String,Map<String,DetailAST>> privateFieldsByType
      Each class's private fields, keyed by simple type name, populated once a class's OBJBLOCK closes. Used to resolve typedUsages.
    • ignoreAnnotationCanonicalNames

      private Set<String> 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

      private Pattern ignoredFieldPattern
      Specify a regular expression pattern for field names to ignore.
    • ignoreAnnotationShortNames

      private Set<String> ignoreAnnotationShortNames
      Set of ignore annotations short names.
  • Constructor Details

    • UnusedPrivateFieldCheck

      public UnusedPrivateFieldCheck()
      Creates a new UnusedPrivateFieldCheck instance with default values.
  • Method Details

    • setIgnoreAnnotationCanonicalNames

      public void setIgnoreAnnotationCanonicalNames(String... annotationNames)
      Setter to specify annotations canonical names which ignore variables in consideration.
      Parameters:
      annotationNames - array of ignore annotations canonical names.
      Since:
      14.1.0
    • setIgnoredFieldPattern

      public void setIgnoredFieldPattern(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. Note this replaces the default value entirely — to keep serialVersionUID ignored 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

      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:
    • getDefaultTokens

      public int[] getDefaultTokens()
      Description copied from class: AbstractCheck
      Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.
      Specified by:
      getDefaultTokens in class AbstractCheck
      Returns:
      the default tokens
      See Also:
    • getRequiredTokens

      public int[] getRequiredTokens()
      Description copied from class: AbstractCheck
      The tokens that this check must be registered for.
      Specified by:
      getRequiredTokens in class AbstractCheck
      Returns:
      the token set this must be registered for.
      See Also:
    • 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
    • visitToken

      public void visitToken(DetailAST ast)
      Description copied from class: AbstractCheck
      Called to process a token.
      Overrides:
      visitToken in class AbstractCheck
      Parameters:
      ast - the token to process
    • leaveToken

      public void leaveToken(DetailAST ast)
      Description copied from class: AbstractCheck
      Called after all the child nodes have been process.
      Overrides:
      leaveToken in class AbstractCheck
      Parameters:
      ast - the token leaving
    • 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
    • resolveUsage

      private static DetailAST resolveUsage(UnusedPrivateFieldCheck.FieldUsage usage)
      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

      private void handleVariableDef(DetailAST ast)
      Collects private field declarations.
      Parameters:
      ast - for this method.
    • hasIgnoredAnnotation

      private boolean hasIgnoredAnnotation(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 in ignoreAnnotationCanonicalNames (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

      private boolean isAnnotatedWithIgnoredAnnotation(DetailAST ast)
      Checks whether the given AST node (a field or a type definition) carries an annotation present in ignoreAnnotationCanonicalNames, 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

      private void handleIdent(DetailAST ast)
      Records field usage, respecting local variable and parameter shadowing. Resolution to a specific field declaration happens later, at finishTree(com.puppycrawl.tools.checkstyle.api.DetailAST).
      Parameters:
      ast - for handleIdent
    • handleDotAccess

      private void handleDotAccess(DetailAST dot, String name)
      Classifies a dot-qualified reference: this.field and ClassName.this.field are 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 via globalUsedFields.
      Parameters:
      dot - the DOT node whose last child is the field IDENT.
      name - the field name being accessed.
    • findDeclaredType

      private String findDeclaredType(String name)
      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

      private static String resolveDeclaredTypeName(DetailAST varOrParamDef)
      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

      private void recordUsage(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.
      Parameters:
      name - the field name referenced.
      qualifierTypeName - the enclosing type name named in a ClassName.this.field reference, or null.
      bareThisQualified - true for a this.field reference.
    • isDeclarationParent

      private static boolean isDeclarationParent(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.
      Parameters:
      parent - the parent of the IDENT being inspected.
      Returns:
      true if the IDENT is a declaration name, not a usage.
    • isPrivate

      private static boolean isPrivate(DetailAST modifiers)
      Checks whether a field is private.
      Parameters:
      modifiers - for isPrivate method.
      Returns:
      modifiers of literal_private.