What javac does
Switch on an enum
A lookup table in a synthetic class, so reordering the enum cannot break the switch.
A switch on an enum looks like a switch on ordinal(), but when the enum is compiled separately its ordinals could change: reorder the constants, recompile only the enum, and every switch would jump to the wrong case. So for java.time.DayOfWeek, javac creates a synthetic class, EnumSwitch$1, holding an int array named $SwitchMap$java$time$DayOfWeek. Its static initialiser fills the array at run time, mapping each case's constant (by its current ordinal) to 1, 2, …, and the switch is on that number.
The source
// A switch on an enum. For an enum compiled separately, javac switches on a table that a synthetic
// class fills in when it first runs; for an enum in the same file, it can switch on ordinal().
import java.time.DayOfWeek;
public class EnumSwitch {
enum Size { SMALL, MEDIUM, LARGE }
static int price(Size size) {
switch (size) {
case SMALL:
return 3;
case MEDIUM:
return 4;
default:
return 5;
}
}
static boolean weekend(DayOfWeek day) {
switch (day) {
case SATURDAY:
case SUNDAY:
return true;
default:
return false;
}
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
weekendreads the array withgetstatic, indexes it withday.ordinal()andiaload, and switches on the result.- Every store into the map is wrapped in a handler for NoSuchFieldError, so if a constant is later removed from the enum, the class still initialises; that case just never matches.
Sizeis declared in the same file, so it is always compiled with the switch. javac 25 switches on itsordinal()directly, with no map.
EnumSwitch.class
static int price(EnumSwitch$Size size)
javac --release 8 to 25 (the same bytecode for every release)
static boolean weekend(DayOfWeek day)
javac --release 8 to 25 (the same bytecode for every release)
EnumSwitch$1.class
A separate class file, EnumSwitch$1.class, that javac generated from the same source.