在System类中in,out、 和err是静态字段。例如,声明了这些字段:
public final static InputStream in = nullInputStream();
为什么要声明nullInputStream()而不是null?
在System类中in,out、 和err是静态字段。例如,声明了这些字段:
public final static InputStream in = nullInputStream();
为什么要声明nullInputStream()而不是null?
源代码有以下注释:
/**
* 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.in是一个static final变量,如果它被设置为null,编译器会将它视为一个常量,并将System.in其他类中的所有引用替换为null(这就是内联的意思)。这显然会使一切都不起作用。一旦系统初始化,必须使用一些本机代码来替换这个System.in最终值的值(通常不应该改变)。
恢复:它用于避免在这种特殊情况下不应该进行的编译器优化,因为 System.in 是一个可以更改的最终字段,这通常是不可能的。
你错了。
在 Java 源代码中,它被写成
public final static InputStream in = null;
不是
public final static InputStream in = nullInputStream();
您可以在此处System参考 该类的源代码。