文章目录
《Lombok 实战 —— @Cleanup & @NonNull》
1. @Cleanup
Automatic resource management: Call your
close()
methods safely with no hassle.
1.1 @Cleanup 入门使用
你可以使用@Cleanup
确保在代码执行后,在退出当前作用域之前自动清除给定资源。你可以通过使用@Cleanup
来注释任何局部变量声明,如下所示:
@Cleanup InputStream in = new FileInputStream(“some/file”);
因此,在局部变量作用范围的末尾,调用in.close()
。 保证通过try/finally
构造运行此调用。 请看下面的示例,看看它是如何工作的。
public class CleanUpTest {
public static void main(String[] args) throws IOException {
File file = new File("fileNameScr");
File file1 = new File("fileNameDest");
@Cleanup InputStream inputStream = new FileInputStream(file);
@Cleanup OutputStream outputStream = new FileOutputStream(file1);
byte[] bytes = new byte[1024];
int len = -1;
while (true) {
len = inputStream.read(bytes);
if (len == -1) {
break;
}
outputStream.write(bytes,0,len);
}
}
}
编译后代码如下:
public class CleanUpTest {
public static void main(String[] args) throws IOException {
File file = new File("fileNameScr");
File file1 = new File("fileNameDest");
FileInputStream inputStream = new FileInputStream(file);
try