什么都不做的 PrintStream

Asg*_*ard 0 java nullpointerexception printstream

我试图使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");
    }
    
    
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 5

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

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

您的“支持为空”消息不会打印,因为在打印super()之前(在调用时)抛出了异常。

只需切换声明的顺序:

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

public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();
Run Code Online (Sandbox Code Playgroud)