什么都不做的 PrintStream

A PrintStream that does nothing

我正在尝试制作一个 PrintStream,它在每次调用其方法时都不执行任何操作。该代码显然没有错误,但是当我尝试使用它时,我得到了 java.lang.NullPointerException: Null output stream。我做错了什么?

public class DoNothingPrintStream extends PrintStream {
    
    public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();

    private static final OutputStream support = new OutputStream() {
        public void write(int b) {}
    };
    // ======================================================
        // TODO | Constructor
    
    /** Creates a new {@link DoNothingPrintStream}.
     * 
     */
    private DoNothingPrintStream() {
        super( support );
        if( support == null )
            System.out.println("DoNothingStream has null support");
    }
    
    
}

问题出在初始化顺序上。静态字段按照您声明它们的顺序(“文本顺序”)初始化,因此 doNothingPrintStreamsupport.

之前初始化

执行doNothingPrintStream = new DoNothingPrintStream();时,support还没有初始化,因为它的声明在doNothingPrintStream的声明之后。这就是为什么在构造函数中,support 为空。

您的“support is null”消息没有被打印出来,因为异常在它被打印之前被抛出(在 super() 调用中)。

只需调换声明的顺序即可:

private static final OutputStream support = new OutputStream() {
    public void write(int b) {}
};

public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();