PrintStream对象out由null初始化,我们如何调用方法呢?

Hit*_*its 9 java printstream

我在System课堂上看到out对象(类型PrintStream)用null值初始化.我们怎么称呼方法 System.out.prinln("");呢?在System类中,out变量像这样初始化:

package java.lang;

public final class System {
    public final static PrintStream out = nullPrintStream();

     private static PrintStream nullPrintStream() throws NullPointerException {
        if (currentTimeMillis() > 0) {
            return null;
        }
        throw new NullPointerException();
     }
}
Run Code Online (Sandbox Code Playgroud)

如上所示,代码out变量由null初始化,并且此变量是final,因此无法进一步初始化,我们如何使用"out"变量.

JB *_*zet 8

解释在评论中:

/**
 * 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().
 */
Run Code Online (Sandbox Code Playgroud)

initializeSystemClass()使用本机方法将标准流初始化为非空值.本机代码可以重新初始化声明为final的变量.


NIN*_*OOP 6

JVM调用private static void initializeSystemClass()初始化它的方法.

看到这两行代码:

setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
Run Code Online (Sandbox Code Playgroud)

这是两种本地方法:

private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);
Run Code Online (Sandbox Code Playgroud)

有一篇很好的文章.