Thursday, August 16, 2007

We have Closeable but still lacks the using statement

.Net has IDisposable and the using statement.

Java5 has Closeable but still lacks the using statement.

I previously blogged about how Closeable can be used, but what would be really nice in Java, was to have a using statement. If we had that, we could write something in the lines of:
using (InputStream is = ...) {
// use is here
Simply as syntactic sugar, as the compiler should just generate this underneath:
InputStream is = null;
try {
is = ...;
// use is here
} catch (IOException e) {
// call close on Closeable here
Maybe .Net has an advantage here, as they have no checked exceptions, so it can better utilize IDisposable everywhere, whereas Java5 Closeable can only be used where IOExceptions are thrown.

Are well, the JCP will be too conservative to just add such sugar...

If we do get closures, me might get to add that statement ourselves. Try and take a look at this page on closure proposals and search for closeAtEnd.

1 comment:

valjok said...

You are right. I use this construct:

new Using[InputStream](new FileInputStream("")) {public void work() {

abstract class Using[T extends Closeable] {
public T closeable;
abstract public void work() throws Exception ;
public Using(T closeable) throws Exception {
this.closeable = closeable;
try {
} finally {

The Closeable is a big deal. Implementing 'using' directive into java compiler is trivial with it.

[InputStream] is a markup for blogger generics.