I expected to find XMLStreamReader
to be AutoCloseable
in Java 7. However, that is not the case. Is there a technical reason why StAX reader/writer interfaces were not (or should not be) retrofitted to implement AutoCloseable
? They already have close methods, whose intent is not different from the close method of AutoCloseable
.
If you look closer to the close()
method of AutoCloseable
:
Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.
Or even Closeable
close()
method :
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
Whereas the close()
method of XMLStreamReader
says :
Frees any resources associated with this Reader. This method does not close the underlying input source.
Indeed the input source is managed by the Reader
which implement the Closeable
interface. So it's the reader that can be close in the try-with-ressource.
For example :
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = null;
try (FileReader fr = new FileReader("file.xml")) { //Will close the FileReader
reader = factory.createXMLStreamReader(fr);
reader.close();
}
catch (XMLStreamException ex) {
if(reader!=null)try {
reader.close();
} catch (XMLStreamException ex1) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex1);
}
}
There is no technical reason why they couldn't have made these things AutoCloseable
. I figure it just comes down to laziness or insufficient time looking for methods called close().
© 2022 - 2024 — McMap. All rights reserved.