Reputation: 439
I know that there must be a variable declaration associated with the resource in the try clause.
But as well being assigned a usual resource instantiation, could it instead be assigned an already existing resource eg :
public String getAsString(HttpServletRequest request) throws Exception {
try (BufferedReader in = request.getReader(); ){
etc
}
}
ie. will the BufferedReader
be closed automatically just like resources instantiated directly in the try clause ?
Upvotes: 1
Views: 88
Reputation: 3978
Yes, BufferedReader
will be closed automatically.
Since Java 7, Interface AutoCloseable
is added as a SuperInterface of Closeable
, so all implementing classes of Closeable
(ie. Resource classes) interface automatically inherit AutoCloseable
interface.
Upvotes: 1
Reputation: 271565
We can test whether this is true using this code:
class Main {
public static void main(String[]args) throws Exception {
AutoCloseable _close = getCloseable()
try (AutoCloseable close = _close) {
// ...
}
}
public static AutoCloseable getCloseable() {
return new MyCloseable();
}
}
class MyCloseable implements AutoCloseable {
@Override
public void close() {
System.out.println("Closing");
}
}
The output is "Closing". This means that indeed, AutoCloseable
s that are created before the try
block will still be closed after the try
block.
Actually, Java does not care what you put in the ()
of the try
block, as long as it implements AutoCloseable
. At runtime, the expression will be automatically evaluated to a value, whether it is a new
expression or not.
Upvotes: 2
Reputation: 120858
Yes. Anything that is AutoCloseable
will call the close
method. try-with-resource will do that.
Upvotes: 4