为什么Java编译器有时允许解除装箱null? [英] Why does the Java compiler sometimes allow the unboxing of null?

查看:183
本文介绍了为什么Java编译器有时允许解除装箱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 可能是自动加载的 int ?为什么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 / em>,它会失败:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆