skip to content

Does the JVM enforce `sealed` or only javac, how does the class file record permitted subtypes, and what do `Class.isSealed` and `getPermittedSubclasses` expose?

level: seniorimportance: should knowfreq 32%

answer

  1. two checkpoints, not one
  2. no flag, an attribute instead
  3. checked while deriving the subclass
  4. IncompatibleClassChangeError for an unlisted subclass
  5. null when not sealed, filtered when sealed

basics

~20 s

javac and the JVM both enforce sealing. The class file records it as a PermittedSubclasses attribute, not a flag, and loading an unlisted subclass throws IncompatibleClassChangeError. Class.isSealed reports sealing; getPermittedSubclasses returns the listed direct subtypes it can load.

solid answer

~50 s

Sealing is enforced twice. `javac` checks the language rules, and the JVM checks again when it derives a class: if the direct superclass or a direct superinterface has a `PermittedSubclasses` attribute and the new class is not named there, or is in a different run-time module, or is non-public in a different run-time package, derivation throws `IncompatibleClassChangeError` (JVMS 5.3.5). There is no `ACC_SEALED` flag: the attribute's presence is what marks a class sealed (JVMS 4.7.31), and a `non-sealed` subclass carries nothing new in its class file. `Class.isSealed()` is true if and only if the class is sealed. `getPermittedSubclasses()` returns `null` for anything not sealed, and otherwise an array of direct subtypes in unspecified order. A listed class that cannot be loaded, or no longer extends the type, is silently left out, so the array can be shorter than the `permits` clause.

code

java · 14 lines
java
import java.util.Arrays;

public class SealedReflection {
    sealed interface Shape permits Circle, Square {}
    record Circle() implements Shape {}
    record Square() implements Shape {}

    public static void main(String[] args) {
        System.out.println(Shape.class.isSealed());       // true
        System.out.println(Arrays.toString(Shape.class.getPermittedSubclasses()));
        System.out.println(Circle.class.isSealed());      // false: a record is implicitly final
        System.out.println(Circle.class.getPermittedSubclasses()); // null, not an empty array
    }
}

go deeper

for a junior

Recall that sealing survives compilation: the class file keeps a list of permitted subtypes, the JVM enforces it when loading a subclass, and Class.isSealed tells you whether a type is sealed.

for a middle

Explain that no sealed flag exists, that a PermittedSubclasses attribute carries the list, and that getPermittedSubclasses returns null for a type that is not sealed and otherwise a filtered array.

for a senior

Diagnose an IncompatibleClassChangeError from the check it names: an unlisted stale binary, a different class loader or a different module. Show you would read the parent's class file and use -Xlog:class+sealed=trace.

for a principal

Treat sealing a published type as a binary-compatibility decision: existing subclasses outside the list stop loading, so weigh the modelling gain against code you do not control, and plan plugin layouts around the same-module check.

## Two enforcement points A **sealed** class or interface limits which classes may directly extend or implement it. The compiler and the JVM both police that limit, and they do not check the same things. `javac` applies the language rules from JLS 8.1.1.2, 8.1.4, 8.1.5 and 8.1.6: - a class naming a sealed direct superclass or superinterface must be one of its permitted direct subclasses (8.1.4, 8.1.5); - a class with a sealed direct supertype must be `final`, `sealed` or `non-sealed` (8.1.1.2); - every class in a `permits` clause must be a direct subclass, in the same named module or, in the unnamed module, the same package (8.1.6). Those rules only reach code compiled against the sealed declaration. A subclass compiled while the parent was still open, a stale JAR on the class path and generated bytecode all bypass them, so the JVM checks again. ## What the JVM checks JVMS 5.3.5 runs the check while deriving a class from its class file. If the direct superclass or a direct superinterface has a `PermittedSubclasses` attribute, derivation throws `IncompatibleClassChangeError` when any of these holds: - the parent is in a different run-time module; - the new class is not `public` and the parent is in a different run-time package; - no entry in the attribute names the new class. HotSpot's message names the failed check, for example `Failed listed permitted subclass check: class Rogue is not a permitted subclass of Base`, and `-Xlog:class+sealed=trace` logs each check. To see it yourself, compile `Rogue extends Base` against an open `Base`, recompile `Base` alone as `sealed` with a different permitted subclass, and load `Rogue`. | Situation | Result | |---|---| | Old binary of a subclass, after the parent is sealed without listing it | `IncompatibleClassChangeError` when it is loaded (JLS 13.4.2.1) | | Class removed from the list, its old binary still present | `IncompatibleClassChangeError` when it is loaded (JLS 13.4.2.1) | | Listed subclass defined by a child class loader | `IncompatibleClassChangeError`, because each loader has its own unnamed module | | New class added to the list | Existing binaries keep linking; an exhaustive `switch` compiled earlier can fail at run time, which belongs with sealed exhaustiveness | The JVM's check is not a copy of the language rules: - **It does not ask for `final`, `sealed` or `non-sealed`.** JVMS 5.3.5 has no such step, so a plain non-final subclass compiled earlier loads if it is listed. - **It allows a `public` subclass in another package of one run-time module.** Compile a two-package module and run it on the class path: both classes land in one unnamed module and load, although `javac` rejects that layout for source in the unnamed module. ## How the class file records it There is no `ACC_SEALED` flag. A class file marks a sealed class by carrying this attribute (JVMS 4.7.31): ```text PermittedSubclasses_attribute { u2 attribute_name_index; u4 attribute_length; u2 number_of_classes; u2 classes[number_of_classes]; } ``` - Each `classes` entry is a constant-pool index of a `CONSTANT_Class_info` naming an authorized direct subclass or subinterface. - The list is always explicit: when source omits `permits`, the compiler writes the inferred classes in. - The attribute appears at most once, and never with `ACC_FINAL`. - It was first defined in class-file version 61.0, Java SE 17. - A `non-sealed` subclass carries nothing new in its class file; the JVM only consults the parent's list. - An `enum` with a constant that has a class body is implicitly sealed (JLS 8.9), and its class file carries the attribute. `javap -v` prints the attribute as `PermittedSubclasses:`. ## What reflection exposes | Receiver | `isSealed()` | `getPermittedSubclasses()` | |---|---|---| | Sealed class or interface | `true` | A non-null array, possibly empty | | Class or interface that is not sealed | `false` | `null` | | Primitive type, `void` or array type | `false` | `null` | Four behaviours catch people out: - **`null`, not empty.** JEP 409's prose says a class that is not sealed gets an empty array; the method's Javadoc and code return `null`. Test `isSealed()` first or handle `null`. - **The array is filtered.** It holds direct subtypes only, in unspecified order. A listed class that cannot be loaded through the receiver's defining loader is silently left out, and so is one that no longer directly extends the receiver, so `isSealed()` can be `true` with an empty array. - **It loads classes.** The method attempts to obtain each `Class` object, and `isSealed()` is implemented as `getPermittedSubclasses() != null`, so in Java 25 and 27 it loads them too. - **`non-sealed` has no accessor.** `Class` has no `isNonSealed()` method, and `Modifier` has no sealed bit. `Class.toGenericString()` prints `non-sealed` by looking for a sealed direct supertype in its private `hasSealedAncestor` helper, so that word is a conclusion, not a stored fact. ## Diagnosing a failure - Read which check the message names: listed, module or package. - Run `javap -v` on the sealed parent as deployed and compare its list with the subclass you expected; a stale JAR is a likely cause. - For a same-module failure, compare both classes' `getClassLoader()` and `getModule()`, since HotSpot's message prints each side's loader. - Turn on `-Xlog:class+sealed=trace` to watch every check as classes load.

  • Why can a subclass on the `permits` list still fail to load when a child class loader defines it?
    JVMS 5.3.5 also requires the same run-time module, and a loader's unnamed module is distinct from those of other loaders. The subclass and its parent therefore differ, and derivation throws `IncompatibleClassChangeError`; HotSpot reports `Failed same module check`. `getPermittedSubclasses()` on the parent, resolving through the parent's own loader, omits that subclass too.
  • Can a class generated at run time subclass a sealed type?
    Only if it passes the same derivation checks: named on the list, in the same run-time module, and in the same run-time package unless public. An unlisted name gets `IncompatibleClassChangeError`. For a sealed interface, `java.lang.reflect.Proxy` refuses even earlier: `newProxyInstance` throws `IllegalArgumentException`.
  • What happens to existing binaries when you add a permitted subclass, or remove one?
    JLS 13.4.2.1 calls adding one binary compatible: earlier class files keep linking, although an exhaustive `switch` compiled earlier can throw `MatchException` when it meets the new subtype. Removing one is not: the removed class's old binary gets `IncompatibleClassChangeError` when it is loaded.
  • Can calling `Class.isSealed()` have a visible side effect?
    Yes, class loading. In Java 25 and 27, `isSealed()` is implemented as `getPermittedSubclasses() != null`, and that method attempts to obtain each listed class through the receiver's defining loader. A class that cannot be obtained is silently ignored, so a missing class does not make the call fail, but `-Xlog:class+load` shows the permitted subclasses loading.

  • Sealing is only a compile-time check, so a separately compiled subclass can still load.
  • The class file marks a sealed class with an ACC_SEALED flag beside ACC_FINAL.
  • getPermittedSubclasses returns an empty array for a class that is not sealed.
  • The array always holds every class in the permits clause, in declaration order.
  • The non-sealed modifier is recorded in the subclass's class file.
  • The JVM re-checks that every permitted subclass is final, sealed or non-sealed.

Sealed classes and interfaces
Java 17pre-release 15
Class.isSealed
Java 17pre-release 15
Class.getPermittedSubclasses
Java 17pre-release 16

Assumes Java 27; sealed classes are final since 17 after previews in 15 and 16, and Java 25 has the same reflection code and load-time checks.

context