Home > Blockchain >  Java try with resources and `AutoCloseable` interface
Java try with resources and `AutoCloseable` interface

Time:06-16

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?

CodePudding user response:

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 constructor is like:

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

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;
    }
}

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".

CodePudding user response:

In a Try with Resource like this:

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}

Three actions occur:

  • The resource writer is acquired in braces: (PrintWriter writer = new PrintWriter(new File("test.txt")))

  • The resource is used inside curly braces: writer.println("Hello World");

  • Resource is closed and freed up automatically when we exit the Try with Resource block

And this resource only is accessible inside corresponding block.

  • Related