Java AutoCloseableを実装したクラスを、try-with-resourcesで書く




try-with-resources文は便利ですよね。
こんな感じで、自作クラスでも使えます。

AutoCloseableを実装したクラスを使って、try-with-resourcesで書くサンプル

何らかの処理をするクラスに、AutoCloseableインターフェースを実装。
何らかの処理をするクラスを、try-with-resourcesで記述してみます。

実行結果

何らかの処理をするクラスの実行結果(+クローズ)が出力されます。

サンプルの解説

try-with-resources文は、AutoCloseableインターフェースを実装したクラスで使うことができます。
close()メソッドで終了処理を記述すれば、try-with-resourcesを抜けるときに、自動的に終了処理が実行されます。