gpt4 book ai didi

java - eclipse 错误?仅使用默认情况打开 null

转载 作者:IT老高 更新时间:2023-10-28 21:03:47 24 4
gpt4 key购买 nike

我正在尝试使用 enum,我发现以下在 Eclipse 上编译并运行良好(Build id:20090920-1017,不确定确切的编译器版本):

public class SwitchingOnAnull {
enum X { ,; }
public static void main(String[] args) {
X x = null;
switch(x) {
default: System.out.println("Hello world!");
}
}
}

当使用 Eclipse 编译和运行时,它会打印 "Hello world!" 并正常退出。

使用 javac 编译器,这会按预期抛出 NullPointerException

那么 Eclipse Java 编译器有 bug 吗?

最佳答案

这是一个错误。这是根据 Java 语言规范,第 3 版switch 语句指定的行为:

JLS 14.11 The switch Statement

SwitchStatement:
switch ( Expression ) SwitchBlock

When the switch statement is executed, first the Expression is evaluated. If the Expression evaluates to null, a NullPointerException is thrown and the entire switch statement completes abruptly for that reason.

显然 Eclipse 中的错误与 default case 或 enum 完全无关。

public class SwitchingOnAnull {
public static void main(String[] args) {
java.math.RoundingMode x = null;
switch(x) {};

switch((Integer) null) {};

switch((Character) null) {
default: System.out.println("I've got sunshine!");
}
}
}

上面的代码在(至少某些版本的)Eclipse 上编译并“正常”运行。当使用 javac 编译时,每个单独的 switch 都会抛出 NullPointerException,这正是规范要求的。


原因

这里是在Eclipse下编译时的javap -c SwitchingOnAnull:

Compiled from "SwitchingOnAnull.java"
public class SwitchingOnAnull extends java.lang.Object{
public SwitchingOnAnull();
Code:
0: aload_0
1: invokespecial #8; //Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: aconst_null
1: astore_1
2: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
5: ldc #22; //String I've got sunshine!
7: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
10: return

}

Eclipse 编译器似乎完全摆脱了整个 switch 结构。不幸的是,这种优化违反了语言规范。


官方说法

该错误已提交并分配修复。

Olivier Thomann 2010-05-28 08:37:21 EDT

We are too aggressive on the optimization.

For:

  switch((Integer) null) {};

we optimize out the whole switch statement when we should at least evaluate the expression.

I'll take a look.

Candidate for 3.6.1.

另见

关于java - eclipse 错误?仅使用默认情况打开 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2926854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com