Preview flag required at runtime is not checked at compile time
Stephan Herrmann
stephan.herrmann at berlin.de
Thu Jan 23 10:03:49 UTC 2025
Using javac versions 23 and 24-ea it is possible to compile the following
program without passing `--enable-preview`:
public class Test {
public static void main(String[] args) {
new Test().d(true);
}
void d(Boolean b) {
switch (b) {
case true -> System.out.println("1");
case false -> System.out.println("2");
};
}
}
When trying to run this program the following exception is thrown:
Exception in thread "main" java.lang.BootstrapMethodError: bootstrap method
initialization exception
at
java.base/java.lang.invoke.BootstrapMethodInvoker.invoke(BootstrapMethodInvoker.java:187)
at java.base/java.lang.invoke.CallSite.makeSite(CallSite.java:316)
at
java.base/java.lang.invoke.MethodHandleNatives.linkCallSiteImpl(MethodHandleNatives.java:275)
at
java.base/java.lang.invoke.MethodHandleNatives.linkCallSite(MethodHandleNatives.java:265)
at Test.d(Test.java:8)
at Test.main(Test.java:4)
Caused by: java.lang.IllegalArgumentException: label with illegal type found:
class java.lang.Boolean
at
java.base/java.lang.runtime.SwitchBootstraps.verifyLabel(SwitchBootstraps.java:214)
at
java.base/java.lang.runtime.SwitchBootstraps.typeSwitch(SwitchBootstraps.java:188)
at
java.base/java.lang.invoke.BootstrapMethodInvoker.invoke(BootstrapMethodInvoker.java:143)
... 5 more
Only when running with --enable-preview the program executes as expected.
This confirms that the compiler should have checked the preview flag, so that
execution without --enable-preview would signal the following, rather than the
BootstrapMethodError:
Error: LinkageError occurred while loading main class Test
java.lang.UnsupportedClassVersionError: Preview features are not
enabled for Test (class file version 67.65535). Try running with '--enable-preview'
The same observation also holds for other pairs of types like Long + long.
best,
Stephan
More information about the compiler-dev
mailing list