为什么 Java 编译器有时会允许对 null 进行拆箱? [英] Why does the Java compiler sometimes allow the unboxing of null?
问题描述
例如:
int anInt = null;
在编译时失败,但是
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("" + getSomeVal());
}
}
public static int getSomeVal() {
return new Random().nextBoolean() ? 1 : null;
}
在运行时失败(通常).尝试只返回 null
也会导致编译错误,所以我假设有多个路径会导致编译器推断 null
可能是一个自动装箱 <代码>整数代码>?javac为什么不能编译两种情况都出现同样的错误?
fails (usually) at run time. Trying to return just null
will also result in a compile error, so I assume there is something about having multiple paths that causes the compiler to infer that null
is potentially an autoboxed int
? Why can javac not fail to compile both cases with the same error?
推荐答案
在第一种情况下,编译器知道您正在尝试对 null
的编译时常量进行拆箱.
In the first case, the compiler knows that you're trying to unbox a compile-time constant of null
.
在第二种情况下,条件表达式的类型是 Integer
,因此您可以有效地编写:
In the second case, the type of the conditional expression is Integer
, so you're effectively writing:
Integer tmp = new Random().nextBoolean() ? 1 : null;
return (int) tmp;
...所以拆箱不会发生在常量表达式上,编译器会允许它.
... so the unboxing isn't happening on a constant expression, and the compiler will allow it.
如果你改变它来强制条件表达式的类型为 int
取消装箱那里,它会失败:
If you changed it to force the conditional expression to be of type int
by unboxing there, it would fail:
// Compile-time failure
return new Random().nextBoolean() ? 1 : (int) null;
这篇关于为什么 Java 编译器有时会允许对 null 进行拆箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!