What javac does
Pattern-matching switch
SwitchBootstraps.typeSwitch picks the case; guards jump back and try again.
A switch on types cannot use a table of constants, so javac (Java 21) asks the JDK which case matches: an invokedynamic to SwitchBootstraps.typeSwitch, given the object and a case index to start from, returns the index of the first case whose type matches, or -1 for null. A tableswitch then jumps to that case, which casts the object and binds the variable.
The source
// min-release: 21
// A pattern switch: one invokedynamic picks the case, then each case casts and binds.
public class PatternSwitch {
static String describe(Object o) {
return switch (o) {
case null -> "null";
case Integer i when i > 100 -> "a big int";
case Integer i -> "the int " + i;
case String s -> "a string of length " + s.length();
default -> "something else";
};
}
}Compiled by javac 25 with -g and --release 21 to 25. Where releases produce different bytecode, each version is shown.
What to look for
case nullis index -1 in thetableswitch.- The guard (
when i > 100) is ordinary code inside the case. If it fails, javac sets the start index to 1 and jumps back to calltypeSwitchagain, so matching resumes at the next case. - The bootstrap arguments are the case types in order: Integer, Integer, String.
PatternSwitch.class
static String describe(Object o)
javac --release 21 to 25 (the same bytecode for every release)
5
return switch (o) {6
case null -> "null";7
case Integer i when i > 100 -> "a big int";45aload_1
54bipush 100
59iconst_1
60istore_2
8
case Integer i -> "the int " + i;69aload_1
77invokedynamic #21// makeConcatWithConstants(Integer) : String ⇐ StringConcatFactory.makeConcatWithConstants "the int \1"
9
case String s -> "a string of length " + s.length();85aload_1
96invokedynamic #30// makeConcatWithConstants(int) : String ⇐ StringConcatFactory.makeConcatWithConstants "a string of length \1"
10
default -> "something else";5
return switch (o) {109areturn
The bootstrap methods
From the BootstrapMethods attribute of the --release 25 class: each invokedynamic names one of these by index.
SwitchBootstraps.typeSwitch(MethodHandles$Lookup, String, MethodType, Object[]) : CallSite- Class
Integer - Class
Integer - Class
String
- Class
StringConcatFactory.makeConcatWithConstants(MethodHandles$Lookup, String, MethodType, String, Object[]) : CallSite- String
"the int \u0001"
- String
StringConcatFactory.makeConcatWithConstants(MethodHandles$Lookup, String, MethodType, String, Object[]) : CallSite- String
"a string of length \u0001"
- String