using a proxy for try-with-resources


public class NotAutoCloseable {
    public void close() {
        // i'm not that close().
    }
}
try (NotAutoCloseable a = new NotAutoCloseable()) {
    // incompatible types: try-with-resources not applicable to variable type
    // (NotAutoCloseable cannot be converted to AutoCloseable)
}

Let’s make a proxy.

private static final Method CLOSE;

static {
    try {
        CLOSE = AutoCloseable.class.getMethod("close");
    } catch (final NoSuchMethodException nsme) {
        throw new InstantiationError(nsme.getMessage());
    }
}

public static <T> AutoCloseable of(final ClassLoader loader,
                                   final T instance,
                                   final Consumer<T> closer) {
    return (AutoCloseable) Proxy.newProxyInstance(
        loader, new Class<?>[] {AutoCloseable.class},
        (proxy, method, args) -> {
            if (CLOSE.equals(method)) {
                closer.accept(instance);
                return null;
            }
            return method.invoke(instance, args);
        });
}

Not we can make it work with try-with-resources statements.

try (AutoCloseable resource = of(<some>, new NotAutoCloseable(), o -> o.close())) {
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s