Lombokの@Cleanup(lombok.Cleanup)アノテーションの利用サンプルです
JavaでI/O処理のためにInputStreamやOutputStreamを利用している場合、必ずfinally句で順番にリソースをcloseするという処理を記述することになります。
これは処理の本質ではないのですが必要な記述で、結果的にコードを見にくくします。
openしたリソースをcloseする処理を簡略化してくれるのが@Cleanup
アノテーションです。
ただし、Java7からはtry-with-resources構文が使えるため、Java7以降では本アノテーションの出番はあまり無いかもしれません。
■@Cleanupを付与したクラス
closeが必要なリソース各々に@Cleanup
アノテーションを付与します
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import lombok.Cleanup; public class CleanupClient { private static String srcPath = "read/data.txt"; private static String destPath = "write/data.txt"; public static void main(String[] args) { try { copy(srcPath, destPath); } catch (IOException e) { e.printStackTrace(); } } private static void copy(String srcPath, String destPath) throws IOException { @Cleanup InputStream in = new FileInputStream(srcPath); @Cleanup OutputStream out = new FileOutputStream(destPath); byte[] buffer = new byte[1024]; while (true) { int readLen = in.read(buffer); if (readLen == -1) { break; } out.write(buffer, 0, readLen); } } }
■実際に生成されているソースコード
finally句で各リソースのcloseが実行されていることが分かります
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class CleanupClient { private static String srcPath = "read/data.txt"; private static String destPath = "write/data.txt"; public static void main(String[] args) { try { copy(srcPath, destPath); } catch (IOException e) { e.printStackTrace(); } } private static void copy(String srcPath, String destPath) throws IOException { InputStream in = new FileInputStream(srcPath); try { OutputStream out = new FileOutputStream(destPath); try { byte[] buffer = new byte[1024]; while (true) { int readLen = in.read(buffer); if (readLen == -1) { break; } out.write(buffer, 0, readLen); } } finally { if (out != null) { out.close(); } } } finally { if (in != null) { in.close(); } } } }