일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- kotlin
- 코틀린
- GIT
- lombok
- 뉴턴역학
- 자바암호
- 고전역학
- 유닉스
- 파이썬
- android
- Java
- write by chatGPT
- 소프트웨어공학
- flet
- Database
- NIO
- chatGPT's answer
- 자바
- GPT-4's answer
- 인프라
- 시스템
- 자바네트워크
- 웹 크롤링
- 역학
- python
- write by GPT-4
- oracle
- JVM
- 리눅스
- Spring boot
- Today
- Total
Akashic Records
Lombok features - @Cleanup 본문
@Cleanup
Automatic resource management: Call your close() methods safely with no hassle.
Overview
You can use @Cleanup to ensure a given resource is automatically cleaned up before the code execution path exits your current scope. You do this by annotating any local variable declaration with the @Cleanup annotation like so:
@Cleanup InputStream in = new FileInputStream("some/file");
As a result, at the end of the scope you're in, in.close() is called. This call is guaranteed to run by way of a try/finally construct. Look at the example below to see how this works.
If the type of object you'd like to cleanup does not have a close() method, but some other no-argument method, you can specify the name of this method like so:
@Cleanup("dispose") org.eclipse.swt.widgets.CoolBar bar = new CoolBar(parent, 0);
By default, the cleanup method is presumed to be close(). A cleanup method that takes 1 or more arguments cannot be called via @Cleanup.
With Lombok
import lombok.Cleanup; import java.io.*; public class CleanupExample { public static void main(String[] args) throws IOException { @Cleanup InputStream in = new FileInputStream(args[0]); @Cleanup OutputStream out = new FileOutputStream(args[1]); byte[] b = new byte[10000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } } |
Vanilla Java
import java.io.*; public class CleanupExample { public static void main(String[] args) throws IOException { InputStream in = new FileInputStream(args[0]); try { OutputStream out = new FileOutputStream(args[1]); try { byte[] b = new byte[10000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } finally { if (out != null) { out.close(); } } } finally { if (in != null) { in.close(); } } } } |
'Library' 카테고리의 다른 글
Lombok features - @EqualsAndHashCode (0) | 2020.12.21 |
---|---|
Lombok features - @ToString (0) | 2020.12.21 |
Lombok features - @Getter and @Setter (0) | 2020.12.21 |
Lombok features - @NonNull (0) | 2020.12.09 |
Lombok features - val & var (0) | 2020.12.09 |