深入理解 Java 中的 try-with-resource
2017-12-14 14:47
639 查看
文章结茧自:深入理解 Java 中的 try-with-resource
在java1.7之后,新增try-with-resource 方式方法,解决了原始的finally收到释放资源可能出现多层嵌套等弊端。
try-with-resource的实现
首先必须在其资源类上实现AutoClosable接口
调用类
看看最后的打印结果
资源关闭被自动调用了。
在java1.7之后,新增try-with-resource 方式方法,解决了原始的finally收到释放资源可能出现多层嵌套等弊端。
try-with-resource的实现
首先必须在其资源类上实现AutoClosable接口
public class Connection implements AutoCloseable { public void sendData() { System.out.println("正在发送数据"); } @Override public void close() throws Exception { System.out.println("正在关闭连接"); } }
调用类
public class TryWithResource { public static void main(String[] args) { try (Connection conn = new Connection()) { conn.sendData(); } catch (Exception e) { e.printStackTrace(); } } }
看看最后的打印结果
正在发送数据 正在关闭连接
资源关闭被自动调用了。
相关文章推荐
- 深入理解 Java 中的 try-with-resource
- 深入理解 Java try-with-resource 语法糖
- 深入理解Java try-with-resource
- 深入理解 Java 中的 try-with-resource
- 深入理解 Java 中的 try-with-resource
- 深入理解Java try-with-resource【细节2】
- 深入理解java中的try-catch-finally
- [Java开发之路](20)try-with-resource 异常声明
- java 7 新特性之一 try with resource statement
- Java新特性-try-with-resource
- Effective Java 3rd 条目9 try-with-resource优于try-finally
- java-资源管理器try-with-resource
- java - try with resource
- 深入理解Java%20try-with-resource/
- Java7新特性 try-with-resource
- Java-try-with-resource
- java7 try-with-resource
- Java进阶知识点3:更优雅地关闭资源 - try-with-resource及其异常抑制
- Java IO 四大附加接口、try-with-resource
- 使用Java中的Try-With-Resource