java - System.out 声明为 static final 并用 null 初始化?

标签 java reflection stream

<分区>

当我浏览 System.class 时,我发现了一些我觉得很奇怪的东西。当您查看 System.in、System.out、System.err 的声明时,它们被标记为 final static 但也用 null

public final static InputStream in = null;  
public final static PrintStream out = null;  
public final static PrintStream err = null;

既然 final 只能初始化一次,那么如何管理它们呢?
当我们使用 System.out.print("..."); 时很明显 out 不是 null 而是一个 final static 它怎么不是 null

那么谁能解释一下已经声明为 final 的 out 是如何初始化的?

最佳答案

它在静态初始化器中使用 native 代码进行初始化。 在 System.java 的顶部,您有:

/* register the natives via the static initializer.
 *
 * VM will invoke the initializeSystemClass method to complete
 * the initialization for this class separated from clinit.
 * Note that to use properties set by the VM, see the constraints
 * described in the initializeSystemClass method.
 */
private static native void registerNatives();
static {
    registerNatives();
}

registerNatives() 方法将初始化 in/out/err - 它在 native 代码中这样做 - native 代码几乎可以做任何它想做的事情并且不限于所有 java 语言规则。 (尽管您也可以通过反射在 Java 中设置一个已经初始化的 final 字段)

关于java - System.out 声明为 static final 并用 null 初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31743760/

相关文章:

面对 Set 的循环依赖时的 Java 序列化错误

c# - 判断一个结构体是否为没有 "Equals"的默认值;也称为结构的 ReferenceEquals

c++ - 在其他类中声明的私有(private)成员

java - 如何使用 JFreeChart 将数组中的数据绘制成图表?

java - SQLiteDatabase rawQuery() 中的 StringIndexOutOfBoundsException

kotlin - 可变和不可变集合类是同一个 kotlin

Java 等于(): to reflect or not to reflect

java - 如何将大型 XML 文件转换为 stream-like-java 8 对象

c# - 是否可以在 C# 中设置 NetworkStream 对象的 CanRead 和 CanWrite 属性?

java - super . super .func()? - Java多态性