You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何XMLEventReader未实现AutoClosable,无法使用try-with-resources?

为什么XMLEventReader的close()方法无法用于try-with-resources?

这是为什么呢?我注意到XMLEventReader有close()方法,但无法使用以下代码:

try (XMLEventReader reader = ...) { ... }

补充说明

实际情况比我预想的更糟。我需要一个实现AutoClosable接口以自动关闭底层输入源的XMLEventReader。因此仅将AutoCloseable#close委托给XMLEventReader#close是不够的!

XMLInputFactory和XMLEventReader的API没能让我用几行代码甚至lambda表达式实现这个需求。我最终写出了下面的代码,但效果并不理想:

static class SourceClosingXMLEventReader extends EventReaderDelegate implements AutoCloseable {

    private final static XMLInputFactory FACTORY = XMLInputFactory.newInstance();

    static SourceClosingXMLEventReader with(StringReader reader) throws XMLStreamException {
        return new SourceClosingXMLEventReader(FACTORY.createXMLEventReader(reader), reader);
    }

    static SourceClosingXMLEventReader with(InputStream stream) throws XMLStreamException {
        return new SourceClosingXMLEventReader(FACTORY.createXMLEventReader(stream), stream);
    }

    private AutoCloseable underlyingInputSource;

    SourceClosingXMLEventReader(XMLEventReader originalReader, AutoCloseable underlyingInputSource) {
        super(originalReader);
        this.underlyingInputSource = underlyingInputSource;
    }

    /**
     * {@link XMLEventReader#close()} does not close underlying resourcesand does not implement
     * {@link AutoCloseable}, so this overridden method implementation tries to fix it
     */
    @Override
    public void close() throws XMLStreamException {
        try {
            super.close();
        }
        finally {
            try {
                underlyingInputSource.close();
            }
            catch (Exception e) {
                new XMLStreamException(e);
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Bastian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 05:32:37