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

Java 为什么System.in声明为nullInputStream()而不是null?,java,Java,在类中,In、out和err是静态字段。声明这些字段,例如: public final static InputStream in = nullInputStream(); 为什么要声明而不是null?你错了。 在Java源代码中,它被写成 public final static InputStream in = null; 不是 您可以参考系统类的源代码。源代码有以下注释: /** * The following two methods exist because in, out,

在类中,
In
out
err
是静态字段。声明这些字段,例如:

 public final static InputStream in = nullInputStream();

为什么要声明而不是
null

你错了。

在Java源代码中,它被写成

 public final static InputStream in = 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().
 */
<> P>简而言之,自从<代码>系统。在中是一个<代码>静态最终< /COD>变量,如果它被设置为<代码> null <代码>,编译器会认为它是常量,并将替换所有引用到<代码>系统。这显然会让一切都失去功能。必须使用一些本机代码来替换此
系统的值。一旦系统初始化,在
中,最终值(通常不会更改)


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

请在公共最终类系统下检查它{/*第一件事——注册本机/专用静态本机void registerNatives();static{registernations();}/*不要让任何人实例化这个类/私有系统(){}/**这个“标准”输入流。此流已*打开并准备提供输入数据。通常,此流*对应于键盘输入或*主机环境或用户指定的另一个输入源。*/public final static InputStream in=nullInputStream();从何处获得源代码引用?@BhavikAmbani:他没有错。他只是在看JDK 6源代码,而你在看JDK 7。@MarkoTopolnik-这可能是一种特殊的编译器黑客行为,导致它以不同的方式处理特定的编译时常量。@StephenC刚去了JLS,事实上很明显——只有原语类型或字符串可以是编译时常量。这意味着
System.out
不需要特殊的伪值来避免它成为编译时常量!没错,存在
公共静态void setIn(InputStream in)
并且它调用
私有静态本机void setIn0(InputStream in)setIno(InputStream in)和setOut(PrintStream out)的作用是什么?这是不正确的。
null
不是编译时常量!@Arendv.Reinersdorff:那么编译器要么内联非编译时常量,要么内联此nullInputStream()这个技巧是不必要的。你的解释是什么?这就是为什么在JDK7中它被简单地设置为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().
 */