本文介绍了在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方法时初始化。

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");
}


推荐答案

它们稍后会被设置为原生方法 SetIn0 SetOut0 SetErr0

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 方法调用,根据到在线程初始化后调用

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