如何解决什么都不做的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");
}
}
解决方法
问题在于初始化顺序。静态字段按照声明的顺序(“文本顺序”)进行初始化,因此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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。