首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么也不做的PrintStream

什么也不做的PrintStream
EN

Stack Overflow用户
提问于 2020-09-14 18:31:05
回答 1查看 84关注 0票数 0

我正在尝试创建一个PrintStream,它在每次调用它的方法时什么也不做。这段代码显然没有错误,但当我尝试使用它时,我得到了一个java.lang.NullPointerException: Null output stream。我做错了什么?

代码语言:javascript
复制
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");
    }
    
    
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-14 18:45:09

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

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

您的"support is null“消息不会打印出来,因为在打印之前就抛出了异常(在super()调用时)。

只需切换声明的顺序:

代码语言:javascript
复制
private static final OutputStream support = new OutputStream() {
    public void write(int b) {}
};

public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63882553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档