Class.isSealed And PermittedSubclasses Check
Inspect sealed interfaces at runtime with Class.isSealed() and getPermittedSubclasses() to build a closed allowlist before reflection dispatch.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.