Class FinalClassCheck
- 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.design.FinalClassCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public class FinalClassCheck extends AbstractCheck
Checks that a class that has only private constructors and has no descendant classes is declared as final.
To configure the check:
<module name="FinalClass"/>
Example:
final class MyClass { // OK private MyClass() { } } class MyClass { // violation, class should be declared final private MyClass() { } } class MyClass { // OK, since it has a public constructor int field1; String field2; private MyClass(int value) { this.field1 = value; this.field2 = " "; } public MyClass(String value) { this.field2 = value; this.field1 = 0; } } class TestAnonymousInnerClasses { // OK, class has an anonymous inner class. public static final TestAnonymousInnerClasses ONE = new TestAnonymousInnerClasses() { }; private TestAnonymousInnerClasses() { } }
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
final.class
- Since:
- 3.1
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static class
FinalClassCheck.ClassDesc
Maintains information about the class.private static class
FinalClassCheck.TypeDeclarationDescription
Maintains information about the type of declaration.-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private java.util.Map<DetailAST,java.lang.String>
anonInnerClassToOuterTypeDecl
Maps anonymous inner class'sTokenTypes.LITERAL_NEW
node to the outer type declaration's fully qualified name.private java.util.Map<java.lang.String,FinalClassCheck.ClassDesc>
innerClasses
Keeps ClassDesc objects for all inner classes.static java.lang.String
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.private static java.lang.String
PACKAGE_SEPARATOR
Character separate package names in qualified name of java class.private java.lang.String
packageName
Full qualified name of the package.private java.util.Deque<FinalClassCheck.TypeDeclarationDescription>
typeDeclarations
Keeps TypeDeclarationDescription object for stack of declared type descriptions.
-
Constructor Summary
Constructors Constructor Description FinalClassCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
beginTree(DetailAST rootAST)
Called before the starting to process a tree.private java.lang.String
extractQualifiedTypeName(DetailAST typeDeclarationAst)
Extract the qualified type declaration name from given type declaration Ast.int[]
getAcceptableTokens()
The configurable token set.private static int
getAnonSuperTypeMatchingCount(java.lang.String patternTypeDeclaration, java.lang.String typeDeclarationToBeMatched)
Calculates and returns the type declaration matching count whenclassToBeMatched
is considered to be super class of an anonymous inner class.int[]
getDefaultTokens()
Returns the default token a check is interested in.private java.util.Optional<FinalClassCheck.ClassDesc>
getNearestClassWithSameName(java.lang.String className, java.util.function.ToIntFunction<FinalClassCheck.ClassDesc> countProvider)
Get the nearest class with same name.int[]
getRequiredTokens()
The tokens that this check must be registered for.private static java.lang.String
getSuperClassName(DetailAST classAst)
Get super class name of given class.void
leaveToken(DetailAST ast)
Called after all the child nodes have been process.private void
registerAnonymousInnerClassToSuperClass(DetailAST literalNewAst, java.lang.String outerTypeDeclName)
Register to the super class of anonymous inner class that the given class is instantiated by an anonymous inner class.private void
registerNestedSubclassToOuterSuperClasses(java.lang.String qualifiedClassName, FinalClassCheck.ClassDesc currentClass)
Register to outer super class of given classAst that given classAst is extending them.private static boolean
shouldBeDeclaredAsFinal(FinalClassCheck.ClassDesc desc)
Checks whether a class should be declared as final or not.private void
visitClass(DetailAST ast)
Called to process a type definition.private void
visitCtor(DetailAST ast)
Called to process a constructor definition.void
visitToken(DetailAST ast)
Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
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
-
PACKAGE_SEPARATOR
private static final java.lang.String PACKAGE_SEPARATOR
Character separate package names in qualified name of java class.- See Also:
- Constant Field Values
-
innerClasses
private java.util.Map<java.lang.String,FinalClassCheck.ClassDesc> innerClasses
Keeps ClassDesc objects for all inner classes.
-
anonInnerClassToOuterTypeDecl
private java.util.Map<DetailAST,java.lang.String> anonInnerClassToOuterTypeDecl
Maps anonymous inner class'sTokenTypes.LITERAL_NEW
node to the outer type declaration's fully qualified name.
-
typeDeclarations
private java.util.Deque<FinalClassCheck.TypeDeclarationDescription> typeDeclarations
Keeps TypeDeclarationDescription object for stack of declared type descriptions.
-
packageName
private java.lang.String packageName
Full qualified name of the package.
-
-
Constructor Detail
-
FinalClassCheck
public FinalClassCheck()
-
-
Method Detail
-
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 classAbstractCheck
- Returns:
- the default tokens
- See Also:
TokenTypes
-
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 classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
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 classAbstractCheck
- 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 classAbstractCheck
- Parameters:
ast
- the token to process
-
visitClass
private void visitClass(DetailAST ast)
Called to process a type definition.- Parameters:
ast
- the token to process
-
visitCtor
private void visitCtor(DetailAST ast)
Called to process a constructor definition.- 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 classAbstractCheck
- Parameters:
ast
- the token leaving
-
shouldBeDeclaredAsFinal
private static boolean shouldBeDeclaredAsFinal(FinalClassCheck.ClassDesc desc)
Checks whether a class should be declared as final or not.- Parameters:
desc
- description of the class- Returns:
- true if given class should be declared as final otherwise false
-
registerNestedSubclassToOuterSuperClasses
private void registerNestedSubclassToOuterSuperClasses(java.lang.String qualifiedClassName, FinalClassCheck.ClassDesc currentClass)
Register to outer super class of given classAst that given classAst is extending them.- Parameters:
qualifiedClassName
- qualifies class name(with package) of the current classcurrentClass
- class which outer super class will be informed about nesting subclass
-
registerAnonymousInnerClassToSuperClass
private void registerAnonymousInnerClassToSuperClass(DetailAST literalNewAst, java.lang.String outerTypeDeclName)
Register to the super class of anonymous inner class that the given class is instantiated by an anonymous inner class.- Parameters:
literalNewAst
- ast node ofTokenTypes.LITERAL_NEW
representing anonymous inner classouterTypeDeclName
- Fully qualified name of the outer type declaration of anonymous inner class
-
getNearestClassWithSameName
private java.util.Optional<FinalClassCheck.ClassDesc> getNearestClassWithSameName(java.lang.String className, java.util.function.ToIntFunction<FinalClassCheck.ClassDesc> countProvider)
Get the nearest class with same name.The parameter
countProvider
exists because if the class being searched is the super class of anonymous inner class, the rules of evaluation are a bit different, consider the following example-public class Main { static class One { static class Two { } } class Three { One.Two object = new One.Two() { // Object of Main.Three.One.Two // and not of Main.One.Two }; static class One { static class Two { } } } }
Function
countProvider
hadn't usedgetAnonSuperTypeMatchingCount(java.lang.String, java.lang.String)
to calculate the matching count then the logic would have falsely evaluatedMain.One.Two
to be the super class of the anonymous inner class.- Parameters:
className
- name of the classcountProvider
- the function to apply to calculate the name matching count- Returns:
Optional
ofFinalClassCheck.ClassDesc
object of the nearest class with the same name.
-
extractQualifiedTypeName
private java.lang.String extractQualifiedTypeName(DetailAST typeDeclarationAst)
Extract the qualified type declaration name from given type declaration Ast.- Parameters:
typeDeclarationAst
- type declaration for which qualified name is being fetched- Returns:
- qualified name of a type declaration
-
getSuperClassName
private static java.lang.String getSuperClassName(DetailAST classAst)
Get super class name of given class.- Parameters:
classAst
- class- Returns:
- super class name or null if super class is not specified
-
getAnonSuperTypeMatchingCount
private static int getAnonSuperTypeMatchingCount(java.lang.String patternTypeDeclaration, java.lang.String typeDeclarationToBeMatched)
Calculates and returns the type declaration matching count whenclassToBeMatched
is considered to be super class of an anonymous inner class.Suppose our pattern class is
Main.ClassOne
and class to be matched isMain.ClassOne.ClassTwo.ClassThree
then type declaration name matching count would be calculated by comparing every character, and updating main counter when we hit "." or when it is the last character of the pattern class and certain conditions are met. This is done so that matching count is 13 instead of 5. This is due to the fact that pattern class can contain anonymous inner class object of a nested class which isn't true in case of extending classes as you can't extend nested classes.- Parameters:
patternTypeDeclaration
- type declaration against which the given type declaration has to be matchedtypeDeclarationToBeMatched
- type declaration to be matched- Returns:
- type declaration matching count
-
-