LoginSignup
11
9

More than 5 years have passed since last update.

GroovyのwithCloseableでtry-with-resourcesを実現する

Posted at

Java 7で入ったtry-with-resourcesは、リソースの開放忘れを防いでくれて便利なんだけど、Groovyではこの構文が使えなかった。

先日リリースされたGroovy 2.3から、try-with-resources構文を直接使うわけじゃないけど、withCloseableを使うことで実現できた。

class A implements Closeable {
    def print() {
        println "print"
    }

    @Override
    public void close() {
        println "close called."
    }
}

// Closure終わりに自動的にcloseが呼ばれる
new A().withCloseable {
    it.print()
}

ポイントは、リソースを開放したいクラスが Closeable をimplementsすること。AutoCloseableを直接implementsしても使えない。

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9