Skip to content

FinalClassCheck should report private classes without constructor #11338

@pbludov

Description

@pbludov

I have read check documentation: https://checkstyle.org/config_design.html#FinalClass
I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run
I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

/var/tmp $ javac -verbose --enable-preview --source=17 TestClass.java
[checking TestClass]
[loading /modules/java.base/java/io/Serializable.class]
[loading /modules/java.base/java/lang/AutoCloseable.class]
[wrote TestClass$Private.class]
[wrote TestClass.class]
[total 113ms]

/var/tmp $ cat config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
          "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
          "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">

<module name = "Checker">
    <module name="TreeWalker">
		<module name="FinalClass"/>
    </module>
</module>
/var/tmp $ cat TestClass.java
class TestClass {
	private class Private {} // Expected violation
}
/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US"
/var/tmp $ java $RUN_LOCALE -jar checkstyle-9.3-all.jar -c config.xml TestClass.java
Starting audit...
Audit done.

From the check description

Checks that a class which has only private constructors is declared as final.

The specs says that

The default constructor has the same access modifier as the class.

Thus, if a private class has no ctor, it should be declared as final.

Identified here by @rnveach


Migration note:
if users do not like violations on inner classes it can be suppressed/filtered by following filter:

        <module name="SuppressionXpathSingleFilter">
            <property name="checks" value="FinalClassCheck" />
            <property name="query"
                value="//CLASS_DEF[MODIFIERS/LITERAL_PRIVATE and 
                (ancestor::CLASS_DEF or ancestor::ENUM_DEF or ancestor::RECORD_DEF)]" />
        </module>

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions