Sub topic 11
Inspecting sealed hierarchies with reflection
Sealed types are enforced by the compiler and by the JVM. Reflection also lets you read the same information at runtime. This chapter covers the two methods that expose it, a recursive hierarchy walker, a startup check that every permitted subtype is handled, and the limits of what reflection can tell you.
This chapter assumes you can declare sealed types with sealed, permits, final and non-sealed. It also assumes you know records and the basics of java.lang.Class. You need Java 17 or later.
The two methods
Java 17 added two methods to java.lang.Class:
| Method | Returns | Notes |
|---|---|---|
| `isSealed()` | `boolean` | `true` only for a class or interface declared `sealed`. |
| `getPermittedSubclasses()` | `Class<?>[]` | The direct permitted subclasses or subinterfaces. Returns `null` if the type is not sealed. |
Both methods work for sealed classes and sealed interfaces. getPermittedSubclasses() returns only direct children. If a permitted subclass is itself sealed, you must call the method again on it to go deeper.
Here is the smallest useful program. It uses the Shape hierarchy from earlier in the tutorial.
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
public class Main {
public static void main(String[] args) {
System.out.println(Shape.class.isSealed());
for (Class<?> c : Shape.class.getPermittedSubclasses()) {
System.out.println(c.getSimpleName());
}
}
}The first line prints true. The next three lines are the names of the permitted records.
Guard against null
For a type that is not sealed, getPermittedSubclasses() returns null, not an empty array. A loop over the result throws NullPointerException. Check isSealed() first.
Class<?> type = String.class;
Class<?>[] subs = type.getPermittedSubclasses();
System.out.println(subs == null);This prints true, because String is not sealed. Records and enums behave the same way: a record is final, but it is not sealed.
Walking the whole hierarchy
Reflection has no flag for non-sealed. To label each node you combine what you can ask:
- If
isSealed()is true, the class issealed. - If
Modifier.isFinal(getModifiers())is true, the class isfinal. Records are always final. - Otherwise, a permitted subclass must be
non-sealed, because the compiler allows only these three modifiers.
The last rule is valid only for classes that appear in a permitted-subclasses list. For an arbitrary class you cannot tell "non-sealed" from "plain open class" this way.
The program below uses the Vehicle hierarchy from the modifiers chapter and prints it as a tree.
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
sealed abstract class Vehicle permits Car, Truck, Bike {}
final class Car extends Vehicle {}
sealed class Truck extends Vehicle permits PickupTruck {}
final class PickupTruck extends Truck {}
non-sealed class Bike extends Vehicle {}
class ElectricBike extends Bike {}
public class HierarchyPrinter {
static String kind(Class<?> c) {
if (c.isSealed()) return "sealed";
if (Modifier.isFinal(c.getModifiers())) return "final";
return "non-sealed";
}
static void print(Class<?> type, int depth) {
System.out.println(" ".repeat(depth) + type.getSimpleName() + " (" + kind(type) + ")");
if (type.isSealed()) {
Class<?>[] subs = type.getPermittedSubclasses();
Arrays.sort(subs, Comparator.comparing((Class<?> c) -> c.getSimpleName()));
for (Class<?> sub : subs) {
print(sub, depth + 1);
}
}
}
public static void main(String[] args) {
print(Vehicle.class, 0);
}
}The output is:
Vehicle (sealed)
Bike (non-sealed)
Car (final)
Truck (sealed)
PickupTruck (final)ElectricBike does not appear. Bike is non-sealed, so its subclasses are not tracked and the walk stops there. The recursion follows this decision for every node.
Reading record components
Reflection is most useful when the permitted subtypes are records. Class.isRecord() and Class.getRecordComponents() let you list each variant and its fields. This is how a framework could generate a schema or a serializer for a sealed interface.
import java.lang.reflect.RecordComponent;
import java.util.Arrays;
import java.util.Comparator;
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
public class SchemaDemo {
public static void main(String[] args) {
Class<?>[] variants = Shape.class.getPermittedSubclasses();
Arrays.sort(variants, Comparator.comparing((Class<?> c) -> c.getSimpleName()));
for (Class<?> variant : variants) {
StringBuilder sb = new StringBuilder(variant.getSimpleName()).append("(");
if (variant.isRecord()) {
RecordComponent[] parts = variant.getRecordComponents();
for (int i = 0; i < parts.length; i++) {
if (i > 0) sb.append(", ");
sb.append(parts[i].getName()).append(": ")
.append(parts[i].getType().getSimpleName());
}
}
System.out.println(sb.append(")"));
}
}
}The output is:
Circle(radius: double)
Rectangle(width: double, height: double)
Square(side: double)If you later add a permitted record, this code picks it up with no change. That property is the reason to use reflection here instead of a hand-written list.
A startup check for missing handlers
An exhaustive switch protects you at compile time. Some code cannot use a switch: a registry of handlers, a map of codecs, or a dependency-injection table. Those structures are not checked by the compiler. A short reflective check can fail fast when a new subtype has no entry.
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
public class CoverageCheck {
static void requireCovered(Class<?> sealedType, Set<Class<?>> handled) {
if (!sealedType.isSealed()) {
throw new IllegalArgumentException(sealedType.getName() + " is not sealed");
}
Set<Class<?>> missing = new LinkedHashSet<>(Arrays.asList(sealedType.getPermittedSubclasses()));
missing.removeAll(handled);
if (!missing.isEmpty()) {
throw new IllegalStateException("No handler for " + missing);
}
}
public static void main(String[] args) {
try {
requireCovered(Shape.class, Set.of(Circle.class, Square.class));
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}It prints No handler for [class Rectangle]. Call a check like this from a unit test or from application startup, so the failure appears before a user hits the missing case.
What reflection does not tell you
- Only direct children.
getPermittedSubclasses()does not return grandchildren. You need a recursive walk, as inHierarchyPrinter. - Open branches are invisible. Subclasses of a
non-sealedclass are not listed anywhere. You cannot discoverElectricBikefromVehicle. - No
non-sealedflag.Modifierhas no constant for it. Infer it as shown above, and only for permitted subclasses. - Order is unspecified. Sort before you compare, print or generate code.
- Entries can be missing. The runtime ignores permitted-subclass entries that cannot be loaded or that fail the permitted-subclass checks. The array can therefore, in unusual deployments, be shorter than the permits clause.
Reflection cannot bypass sealing
Sealing is checked when a class is loaded. If a class file claims to extend a sealed class that does not list it, the JVM throws IncompatibleClassChangeError. This can happen if you recompile only the sealed parent and then load an older child. setAccessible(true) has no effect on this rule, and reflection cannot add a permitted subclass.
Dynamic proxies are also affected. java.lang.reflect.Proxy generates a new class that implements the interfaces you pass. Because the generated class is not in the permits list, Proxy.newProxyInstance rejects a sealed interface with IllegalArgumentException. Mocking tools that rely on the same mechanism may have the same problem with sealed types, so check your tool's documentation.
Where this fits
Reflection answers "which subtypes exist right now". It does not replace the compiler's guarantees. Use it for tooling and tests, and use pattern matching for application logic.
Exercise
Why does Class.getPermittedSubclasses() on a record such as Circle return null instead of an empty array, and what should you call first to avoid a NullPointerException?
Show answer
The method returns null for any type that is not sealed, and a record is final but not sealed. Call isSealed() first, and read the array only when it returns true.
Exercise
In HierarchyPrinter, ElectricBike never appears in the output even though it extends Vehicle indirectly. Why?
Show answer
Bike is non-sealed, so the compiler does not track its subclasses. Bike is not sealed, so the walker does not call getPermittedSubclasses() on it, and ElectricBike is never reached.
Exercise
You add record Triangle(double base, double height) implements Shape to the Shape hierarchy and update the permits clause. SchemaDemo needs no edit. A hand-written map of Shape handlers gains no entry for Triangle. Which of the two fails, and when?
Show answer
SchemaDemo does not fail, because it reads getPermittedSubclasses() and finds Triangle. The hand-written map is not checked by the compiler, so Triangle has no handler. A requireCovered check at startup or in a test would throw IllegalStateException, and without one the gap shows up only when a Triangle reaches the map at runtime.