试用JDK/12 EarlyAccess Build 20,其中JEP-325 Switch Expressions已作为预览功能集成。表达式的示例代码(在 JEP 中也是如此):
Scanner scanner = new Scanner(System.in);
Day day = Day.valueOf(scanner.next().toUpperCase());
int i = switch (day) {
case MONDAY,TUESDAY, WEDNESDAY:
break 0;
default:
System.out.println("Second half of the week");
// ERROR! Group doesn't contain a break with value
};
我试图按照上一个问题中关于如何使用 Maven 编译 JDK12 预览功能并使用命令行执行上述代码块的相同过程:
java --enable-preview -jar target/jdk12-updates-1.0.0-SNAPSHOT.jar
出乎我的意料,我收到以下错误:
Error: Unable to initialize main class com.stackoverflow.nullpointer.expression.SwitchExpressionMustComplete Caused by: java.lang.VerifyError: Bad local variable type Exception Details: Location: com/stackoverflow/nullpointer/expression/SwitchExpressionMustComplete.main([Ljava/lang/String;)V @66: iload Reason: Type top (current frame, locals[4]) is not assignable to integer Current Frame: bci: @66 flags: { } locals: { '[Ljava/lang/String;', 'java/util/Scanner', 'com/stackoverflow/nullpointer/Day' } stack: { } Bytecode: 0000000: bb00 0259 b200 03b7 0004 4c2b b600 05b8 0000010: 0006 4db2 0007 2cb6 0008 2eaa 0000 001f 0000020: 0000 0001 0000 0003 0000 0019 0000 0019 0000030: 0000 0019 0336 04a7 000b b200 0912 0ab6 0000040: 000b 1504 3eb1 Stackmap Table: append_frame(@52,Object[#2],Object[#34]) same_frame(@58) same_frame(@66)
我知道该文档指出该代码是错误的,并且将注释替换为break 1;
解决了它,但我的问题是:
Q1。为什么编译阶段同样成功?这不应该在编译时失败吗?
Q2。我看到如此详细的错误消息的原因是什么?该--enable-preview
功能可以对此负责吗?