# 关于 Try-With-Source 的使用以及注意点
# 在 JDK 1.7 之前,资源需要手动关闭
1 | Charset charset = Charset.forName("US-ASCII"); |
在 JDK 7 之前,你一定要牢记在 finally 中执行 close 以释放资源
# JDK 7 中的 try-with-resources 介绍
try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源 (resource) 是指在程序完成后,必须关闭的对象。 try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。
例如,我们自定义一个资源类
1 | public class Demo { |
执行输出如下:
1 | do something |
可以看到,资源终止被自动关闭了。
再来看一个例子,是同时关闭多个资源的情况:
1 | public class Main2 { |
最终输出为:
1 | do something |
# try-with-resources 在 JDK 9 中的改进
作为 Milling Project Coin 的一部分, try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。
例如,给定资源的声明
1 | // A final resource final Resource resource1 = new Resource("resource1"); |
老方法编写代码来管理这些资源是类似的:
1 | // Original try-with-resources statement from JDK 7 or 8 |
而新方法可以是
1 | // New and improved try-with-resources statement in JDK 9 |
# 使用注意点
类似于 java.io.InputStream、java.sql.Connection 等都是可以使用该语法实现自动关闭,是因为他实现了 AutoCloseable 接口
所以限制点就在于这个