Thursday, January 09, 2014

Java 8 AutoCloseable trick

I am working with an API some of whose interfaces have a "close()" method but which do not implement AutoCloseable (they predate this JDK addition), yet I would like to use them in a try-resources block. What to do?

Previously I would give up and just do the try/finally dance — Java has no perfect forwarding, implementing a wrapper class preserving the original's calls is terribly hard.

Java 8 provides a neat trick with method references:

interface Foo {
    void close();

    void doFoo();


final Foo foo = new SomeFoo();
try (final AutoCloseable ignored = foo::close) {


A practical use is pre-4 Spring Framework. When a context type in version 4 declares "close", it implements AutoCloseable; version 3 and earlier do not.

Another neat trick here, the method names need not be the same:

interface Bar {
    void die();

    void doBar();


final Bar bar = new SomeBar();
try (final AutoCloseable ignored = bar::die) {

No comments: