UnnecessaryPermitsClause

Since Checkstyle 14.2.0

Description

Checks that a permits clause of a sealed class or interface is not unnecessary, i.e. that it is not possible to omit the clause and have the compiler infer the exact same set of permitted subtypes.

See the Java Language Specification for more information about sealed classes.

This Check does not perform full type resolution. It determines whether a permitted type is local to the file by comparing simple names against every type declaration (class, interface, enum, or record) found anywhere in the compilation unit, including nested and sibling top-level types. As a result, a permitted type whose simple name coincidentally matches an unrelated local type declaration could, in theory, be misidentified as local. In practice this situation cannot occur in code that compiles, since the Java compiler would not be able to resolve such an ambiguous reference in the permits clause.

Examples

To configure the check:


<module name="Checker">
  <module name="TreeWalker">
    <module name="UnnecessaryPermitsClause"/>
  </module>
</module>

Example:


public sealed class Example1 permits SubA, SubB {
    // violation above """Unnecessary 'permits' clause for classes
    // in the same compilation unit."""
}

final class SubA extends Example1 {
}

final class SubB extends Example1 {
}

To configure the check


<module name="Checker">
  <module name="TreeWalker">
    <module name="UnnecessaryPermitsClause"/>
  </module>
</module>

Example:


public sealed interface Example2 permits Example2SubA, Example2SubB {
    // ok as all permitted subclasses are not in same file
}

final class Example2SubA implements Example2 {
}

The second file contains a permitted subclass declared in a separate compilation unit:


public final class Example2SubB implements Example2 {
}

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Fully Qualified Name

com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryPermitsClauseCheck

Use this fully qualified class name in configuration when an exact class reference is required.

Parent Module

TreeWalker