Search code examples
javainterfaceautocloseable

Define own XMLEventReader to implement the Closeable interface


I'd like to use try-with-resources with the XMLEventReader.

As I found out, XMLEventReader is just an interface and the object I get from XMLInputFactory.newInstance().createXMLEventReader(stream) is of the com.sun.xml.internal.stream.XMLEventReaderImpl class.

Normally I would extend that class to implement Closeable. But I'm not able to access it (I can't open it in my IDE).
I found its code online. But I'm not willing to copy it to a new class, just to make it closeable.

So why can't I access that class and what's the best solution to make a Closeable XMLEventReader?


Solution

  • How about this:

    public class CloseableXmlEventReader implements XMLEventReader, AutoCloseable{
    
        private final XMLEventReader internal;
    
        public CloseableXmlEventReader(XMLEventReader internal) {
            this.internal = internal;
        }
    
        @Override
        public XMLEvent nextEvent() throws XMLStreamException {
            return internal.nextEvent();
        }
    
        @Override
        public boolean hasNext() {
            return internal.hasNext();
        }
    
        @Override
        public XMLEvent peek() throws XMLStreamException {
            return internal.peek();
        }
    
        @Override
        public String getElementText() throws XMLStreamException {
            return internal.getElementText();
        }
    
        @Override
        public XMLEvent nextTag() throws XMLStreamException {
            return internal.nextTag();
        }
    
        @Override
        public Object getProperty(String name) throws IllegalArgumentException {
            return internal.getProperty(name);
        }
    
        @Override
        public void close() throws XMLStreamException {
            internal.close();
        }
    
        @Override
        public Object next() {
            return internal.next();
        }
    }
    

    Use like this:

    try(CloseableXmlEventReader reader = 
            new CloseableXmlEventReader(XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream("test.xml")))) {
    
    } catch (XMLStreamException | FileNotFoundException ex) {
        Logger.getLogger(CloseableXmlEventReader.class.getName()).log(Level.SEVERE, null, ex);
    }