It turns out that almost nobody closes resources in Java correctly. Programmers either do not use try-finally
block at all, or just put resource.close()>
Though anonymous class is quite verbose, it's still acceptable in java land
new TryWithResource(){
protected InputStream init() throws Exception {
return new FileInputStream("abc.txt");
}
protected void use(InputStream input) throws Exception{
input.read();
}
};
----
abstract class TryWithResource
{
abstract protected R init() throws Exception;
abstract protected void use(R resource) throws Exception;
// caution: invoking virtual methods in constructor!
TryWithResource() throws Exception
{
// ... code before
R r = init();
use(r);
// ... code after
}
}