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

use*_*722 10 java

Systemin,outerr在静态字段.例如,声明这些字段:

 public final static InputStream in = nullInputStream();
Run Code Online (Sandbox Code Playgroud)

为什么要申报nullInputStream()而不是null

JB *_*zet 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().
 */
Run Code Online (Sandbox Code Playgroud)

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

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