Class.isSealed And PermittedSubclasses Check

Inspect sealed interfaces at runtime with Class.isSealed() and getPermittedSubclasses() to build a closed allowlist before reflection dispatch.

JavaSecurity Boundaries

Code

snippet
import java.util.Arrays;
import java.util.Set;

public class SealedAllowlistGuard {

    sealed interface Command permits StartCmd, StopCmd {}
    record StartCmd(String service) implements Command {}
    record StopCmd(int code) implements Command {}
    record RogueCmd(String service) {}

    public static void main(String[] args) {
        Class<?> base = Command.class;
        System.out.println("Command.isSealed:  " + base.isSealed());
        System.out.println("StartCmd.isSealed: " + StartCmd.class.isSealed());

        // getPermittedSubclasses() returns null when called on a non-sealed class
        Class<?>[] permitted = base.getPermittedSubclasses();
        Set<Class<?>> allowlist = permitted == null
                ? Set.of()
                : Set.copyOf(Arrays.asList(permitted));

        System.out.println("permitted count:   " + allowlist.size());
        System.out.println("StartCmd allowed:  " + allowlist.contains(StartCmd.class));
        System.out.println("StopCmd allowed:   " + allowlist.contains(StopCmd.class));
        System.out.println("RogueCmd allowed:  " + allowlist.contains(RogueCmd.class));
    }
}

Annotated execution — Class.isSealed And PermittedSubclasses Check

The snippet is organized around the classes SealedAllowlistGuard, Command, StartCmd and StopCmd and the function main.

What to watch for

  • Import declarations listed exclusively reference built-in standard modules.

Applying it

Entry signature: public static void main(String[] args)

The run emits 6 labeled sections — Command.isSealed:, StartCmd.isSealed:, permitted count:, StartCmd allowed:, StopCmd allowed:, RogueCmd allowed: — one per step.

Statements that matter

Class<?>[] permitted = base.getPermittedSubclasses();
Set<Class<?>> allowlist = permitted == null
        ? Set.of()
        : Set.copyOf(Arrays.asList(permitted));
Class<?> base = Command.class;

Interactive Tools for This Topic

FAQ

What does Class.isSealed And PermittedSubclasses Check print when run?
No setup needed: run the file and look for labeled lines like `Command.isSealed:`, `StartCmd.isSealed:`, `permitted count:` in the output.