6
\$\begingroup\$

I made this utility class to convert Closeable instances to AutoCloseable, so that I can make use of the try-with-resource exception handling mechanism of Java7. This is mainly useful for code which can not be altered.

public class AutoClose<T extends Closeable> implements AutoCloseable, Closeable {

    public final T instance;

    private AutoClose(T instance) {
        this.instance = instance;
    }

    public static <T extends Closeable> AutoClose<T> of(T instance) {
        return new AutoClose<>(instance);
    }

    @Override
    public void close() throws IOException {
        instance.close();
    }
}

usage can be like :

try (AutoClose<SomeType> auto = AutoClose.of(someCloseable)) {
    auto.instance.someWork();
}

feedback much appreciated.

\$\endgroup\$
12
\$\begingroup\$

I'll try to say this the best way I can...

Completely useless unnecessary!

Sorry. I couldn't find any better way to say it. The code that you have is well-written, but it is not necessary in the first place.

The reason is that the interface Closeable already lists AutoCloseable as a "superinterface", which means that Closeable extends AutoCloseable. So all Closeable objects are already AutoCloseable.

Which means that your code:

try (AutoClose<SomeType> auto = AutoClose.of(someCloseable)) {
    auto.instance.someWork();
}

Can instead be simply:

try (SomeType auto = someCloseable) {
    auto.someWork();
}

There is no need for your AutoClose wrapper.

\$\endgroup\$
  • 10
    \$\begingroup\$ Good lord. Time to sleep........ \$\endgroup\$ – Dexter Sep 21 '16 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.