PrintStream のソースを見てください。
基礎となる Writer への 2 つの参照textOut
、charOut
1 つは文字ベース、もう 1 つはテキストベース (意味は何でも) を持っています。また、バイトベースの OutputStream への 3 番目の参照を継承しますout
。
/**
* Track both the text- and character-output streams, so that their buffers
* can be flushed without flushing the entire stream.
*/
private BufferedWriter textOut;
private OutputStreamWriter charOut;
メソッドではclose()
、それらすべてを閉じます(textOut
基本的には と同じcharOut
です)。
private boolean closing = false; /* To avoid recursive closing */
/**
* Close the stream. This is done by flushing the stream and then closing
* the underlying output stream.
*
* @see java.io.OutputStream#close()
*/
public void close() {
synchronized (this) {
if (! closing) {
closing = true;
try {
textOut.close();
out.close();
}
catch (IOException x) {
trouble = true;
}
textOut = null;
charOut = null;
out = null;
}
}
}
ここで興味深いのは、charOut には、PrintStream 自体を参照する (ラップされた) が含まれていることです (init(new OutputStreamWriter(this))
コンストラクターの に注意してください)。
private void init(OutputStreamWriter osw) {
this.charOut = osw;
this.textOut = new BufferedWriter(osw);
}
/**
* Create a new print stream.
*
* @param out The output stream to which values and objects will be
* printed
* @param autoFlush A boolean; if true, the output buffer will be flushed
* whenever a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline
* character or byte (<code>'\n'</code>) is written
*
* @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
*/
public PrintStream(OutputStream out, boolean autoFlush) {
this(autoFlush, out);
init(new OutputStreamWriter(this));
}
そのため、 への呼び出しはclose()
を呼び出しcharOut.close()
、それが再びオリジナルを呼び出します。close()
これが、無限再帰を短くするための終了フラグを持っている理由です。