本文介绍了在 System.java 源代码中,标准输入、输出和错误流被声明为 final 并初始化为 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但众所周知,这些流默认连接到控制台并且已经打开.System 类 setIn()、setOut 和 setErr() 中还有一些方法可以重定向流.当它们被声明为 final 并设置为初始化值 null 时,这怎么可能?

But as we very well know, these streams are connected to the console by default and already open. There are also methods in the System class setIn(), setOut, and setErr() to redirect the streams. How is any of this possible when they have been declared final and set to the initialization value null?

我编译了以下代码,在调用 println() 时设置断点并使用 netbeans 进行调试.我的目标是通过进入源来确定变量 System.in 何时被初始化为标准输出.但似乎在调用 main 方法时输出流 out 已经初始化.

I compiled the following code, set a breakpoint at the call to println() and debugged using netbeans. My objective was to determine exactly when the variable System.in is initialized to the standard output by stepping into the source. But it seems that the output stream out is already initialized by the time the main method is called.

public static void main(String[] args) {
    System.out.println("foo");
}

推荐答案

它们稍后由本地方法 SetIn0SetOut0SetErr0 设置>

They are later on set by native methods SetIn0, SetOut0 and SetErr0

private static native void setIn0(InputStream in);
private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);

initializeSystemClass 方法调用,该方法根据 JavaDoc 在线程初始化后调用.

called from the initializeSystemClass method, which according to the JavaDoc is called after thread initialization.

FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));

这篇关于在 System.java 源代码中,标准输入、输出和错误流被声明为 final 并初始化为 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:29