在System
class、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
(这就是内联的意思)。这显然会使一切都无法正常工作。系统初始化后,必须使用一些 native 代码来替换此 System.in
最终值(通常不应更改)的值。
恢复:它用于避免在这种非常特殊的情况下不应该进行的编译器优化,因为 System.in 是可以更改的最终字段,这通常是不可能的。
关于java - 为什么 System.in 声明为 nullInputStream() 而不是 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10774165/