LoginSignup
1
0

More than 1 year has passed since last update.

ラムダ式でtry-with-resources文にクローズ処理以外の後片付けをさせる方法

Last updated at Posted at 2022-02-26

概要

try-with-resources文の自動クローズを利用するにはリソースにAutoCloseableインターフェースが実装されている必要があるが、このインターフェースを持たないクラスに対してもラムダ式を使って自動クローズするさせる方法についてメモ

try-with-resources文で自動クローズされる仕組み

ドキュメントを確認してみたところ、try-with-resources文の中でオープンされたリソースのAutoCloseabelインターフェースがtry文を抜ける際に呼び出されてクローズ処理が行われるからという理解でよさそう

HttpURLConnectionと自動クローズ

AutoCloseableインターフェースを持っているリソースの自動クローズをしてくれるtry-with-resources文だが、例えばHttpURLConnectionのようなclose処理があるがこのインターフェースを持っていないクラスでは利用できない
(HttpURLConnectionで行うのはConnectからのDisconnect処理なので、そもそもClose処理ではないけれど・・)

try(この中でオープン出来るリソースはAutoCloseableインターフェースを持っていないといけない) {
  ~~
}

AutoCloseableとラムダ式

AutoCloseableインターフェースは、単一のメソッドのみを持つため以下のようなラムダ式で記述することができる

AutoCloseable autoCloseabel = () -> httpURLConnection.disconnect();

try-with-resources文とラムダ式

これがわかれば、以下の様にしてHttpURLConnectionを自動クローズ自動切断することができる

HttpURLConnection httpURLConnection = new HttpURLConnection();
httpURLConnection .connect();

try(AutoCloseable autoCloseabel = () -> httpURLConnection.disconnect();) {
  ~~
}

もう一工夫して、以下の様に接続処理を実行して、それを切断するラムダ式を返すメソッドを用意することで

AutoCloseable connect(HttpURLConnection conn) {
  conn.connect();
  return () -> conn.disconnect();
}

それをtry-with-resources文の中で呼び出だせば、見た目をすっきり記述することもできる

try(AutoCloseable autoCloseable = connect(conn);) {
  ~~
}

ここまでするくらいなら、try文にfinally句を追加して終了処理を記述した方が手っ取り早いが・・

1
0
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
1
0