问题描述
我正在尝试制作一个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");
}
}
解决方法
问题在于初始化顺序。静态字段按照声明的顺序(“文本顺序”)进行初始化,因此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();