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?

Answers


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);
}

Need Your Help

Google maps .setMap issue for IE8

javascript internet-explorer google-maps google-maps-api-3 internet-explorer-8

So I've got a bit of a problem here. This script works fine in all browsers apart from IE8

changing font size of UIButton

iphone objective-c

I have a UIButton which displays a text, with the following code:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.