Class 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
    • Method Detail

      • 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:
        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 class AbstractCheck
        Parameters:
        rootAST - the root of the tree
      • 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
      • 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 class
        currentClass - 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 of TokenTypes.LITERAL_NEW representing anonymous inner class
        outerTypeDeclName - Fully qualified name of the outer type declaration of anonymous inner class
      • getNearestClassWithSameName

        private java.util.Optional<FinalClassCheck.ClassDescgetNearestClassWithSameName​(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 {
                     }
                 }
             }
         }
         
         
        If the Function countProvider hadn't used getAnonSuperTypeMatchingCount(java.lang.String, java.lang.String) to calculate the matching count then the logic would have falsely evaluated Main.One.Two to be the super class of the anonymous inner class.
        Parameters:
        className - name of the class
        countProvider - the function to apply to calculate the name matching count
        Returns:
        Optional of FinalClassCheck.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 when classToBeMatched is considered to be super class of an anonymous inner class.

        Suppose our pattern class is Main.ClassOne and class to be matched is Main.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 matched
        typeDeclarationToBeMatched - type declaration to be matched
        Returns:
        type declaration matching count