我正在尝试创建一个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");
}
}发布于 2020-09-14 18:45:09
问题出在初始化顺序上。静态字段按照您声明的顺序进行初始化(“文本顺序”),因此在support之前初始化doNothingPrintStream。
在执行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();https://stackoverflow.com/questions/63882553
复制相似问题