为什么System.in声明为nullInputStream()而不是null?

时间:2012-05-27 13:01:03

标签: java

System课程中,inouterr是静态字段。例如,声明了这些字段:

 public final static InputStream in = nullInputStream();

为什么要声明nullInputStream()而不是null

2 个答案:

答案 0 :(得分:10)

源代码有以下注释:

/**
 * The following two methods exist because in, out, and err must be
 * initialized to null.  The compiler, however, cannot be permitted to
 * inline access to them, since they are later set to more sensible values
 * by initializeSystemClass().
 */

简而言之,由于System.instatic final变量,如果它设置为null,编译器会将其视为常量,并将替换所有对{System.in的引用。 1}}在null的其他类中(这就是内联的意思)。这显然会使一切都失去功能。系统初始化后,必须使用一些本机代码替换此System.in最终值(通常不应更改)的值。

要恢复:它用于避免在这种特殊情况下不应该进行的编译器优化,因为System.in是一个可以改变的最终字段,这通常是不可能的。

答案 1 :(得分:-1)

你错了。

在Java源代码中,它被写为

 public final static InputStream in = null;

不是

 public final static InputStream in = nullInputStream();

您可以参考Systemhere的源代码。