Java try with resources and `AutoCloseable` interface

Viewed 132

I am looking for a Java equivalent for python's with statement, and I read about implementing the AutoCloseable interface and using try with resources.

In python, the context manager (with statement) uses two methods: __enter__ and __exit__, but in Java, the try with resources block uses only close, which is the equivalent of __exit__.

Is there an equivalent for the __enter__ method, in order to perform a certain method automatically when entering the try with resources block, and not only when the block is over?

1 Answers

The equivalent is basically whatever you are calling in the try to get an instance of your AutoCloseable. This could be a constructor like:

try (MyClass obj = new MyClass()) { …

Where the class having such a constructor looks like:

public class MyClass implements AutoCloseable {
    public MyClass() {
        // do "enter" things...
    }

    @Override
    public void close() {
        // close resources
    }
}

Depending on what you need "enter" to do, you might instead prefer a static producer for your class, which would look like this:

try (MyClass obj = MyClass.getInstance(someProperties)) { …

Then your class might look something like this:

public class MyClass implements AutoCloseable {
    private MyClass() {
        // instantiate members
    }

    public static MyClass getInstance(Properties config) {
        // you could implement a singleton pattern or something instead, for example
        MyClass obj = new MyClass();
        // read properties...
        // do "enter" things...
        return obj;
    }

    @Override
    public void close() {
        // close resources
    }
}

You could even call a factory or builder pattern in the try to produce your AutoCloseable. It all depends on your design and what you need the instance to do on "enter".

Related