在 JDK 9 中更简洁使用 try-with-resources 语句
本文详细介绍了自 JDK 7 引入的 try-with-resources 语句的原理和用法,以及介绍了 JDK 9 对 try-with-resources 的改进,使得用户可以更加方便、简洁的使用 try-with-resources 语句。
在 JDK 7 之前,资源需要手动关闭。
例如下面一个很常见的文件操作的例子:
Charset charset = Charset.forName("US-ASCII");
String s = ...;
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(file, charset);
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
} finally {
if (writer != null) writer.close();
}
在 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 的所有对象),可以使用作为资源。
例如,我们自定义一个资源类
public class Demo {
public static void main(String[] args) {
try(Resource res = new Resource()) {
res.doSome();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
class Resource implements AutoCloseable {
void doSome() {
System.out.println("do something");
}
@Override
public void close() throws Exception {
System.out.println("resource is closed");
}
}
执行输出如下:
do something
resource is closed
可以看到,资源终止被自动关闭了。
再来看一个例子,是同时关闭多个资源的情况:
public class Main2 {
public static void main(String[] args) {
try(ResourceSome some = new ResourceSome();
ResourceOther other = new ResourceOther()) {
some.doSome();
other.doOther();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
class ResourceSome implements AutoCloseable {
void doSome() {
System.out.println("do something");
}
@Override
public void close() throws Exception {
System.out.println("some resource is closed");
}
}
class ResourceOther implements AutoCloseable {
void doOther() {
System.out.println("do other things");
}
@Override
public void close() throws Exception {
System.out.println("other resource is closed");
}
}
最终输出为:
do something
do other things
other resource is closed
some resource is closed
在 try 语句中越是最后使用的资源,越是最早被关闭。
try-with-resources 在 JDK 9 中的改进
作为 Milling Project Coin 的一部分, try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。
例如,给定资源的声明
// A final resource
final Resource resource1 = new Resource("resource1");
// An effectively final resource
Resource resource2 = new Resource("resource2");
老方法编写代码来管理这些资源是类似的:
// Original try-with-resources statement from JDK 7 or 8
try (Resource r1 = resource1;
Resource r2 = resource2) {
// Use of resource1 and resource 2 through r1 and r2.
}
而新方法可以是
// New and improved try-with-resources statement in JDK 9
try (resource1;
resource2) {
// Use of resource1 and resource 2.
}
看上去简洁很多吧。对 Java 未来的发展信心满满。
愿意尝试 JDK 9 这种新语言特性的可以下载使用 JDK 9 快照。Enjoy!
源码
本章例子的源码,可以在 https://github.com/waylau/essential-java 中 com.waylau.essentialjava.exception.trywithresources 包下找到。
参考
- 更多内容可移步至笔者所著开源书《Java 编程要点》
- https://blogs.oracle.com/darcy/entry/concise_twr_jdk9
- http://docs.oracle.com/javase/8/docs/technotes/guides/language/try-with-resources.html
from: https://waylau.com/concise-try-with-resources-jdk9/
在 JDK 9 中更简洁使用 try-with-resources 语句的更多相关文章
- php 中更简洁的三元运算符 ?:
PHP 三元运算符是对参数赋值时候的一个简洁的主要用法. 一个主要的用法: PHP 三元运算符能够让你在一行代码中描述判定代码, 从而替换掉类似以下的代码: <?php if (isset($v ...
- Nashorn 在JDK 8中融合Java与JavaScript之力
从JDK 6开始,Java就已经捆绑了JavaScript引擎,该引擎基于Mozilla的Rhino.该特性允许开发人员将JavaScript代码嵌入到Java中,甚至从嵌入的JavaScript中调 ...
- Java 9 揭秘(20. JDK 9中API层次的改变)
Tips 做一个终身学习的人. 在最后一章内容中,主要介绍以下内容: 下划线作为新关键字 改进使用try-with-resources块的语法 如何在匿名类中使用<>操作符 如何在接口中使 ...
- Nashorn——在JDK 8中融合Java与JavaScript之力
从JDK 6开始,Java就已经捆绑了JavaScript引擎,该引擎基于Mozilla的Rhino.该特性允许开发人员将JavaScript代码嵌入到Java中,甚至从嵌入的JavaScript ...
- Nashorn——在JDK 8中融合Java与JavaScript之力--转
原文地址:http://www.infoq.com/cn/articles/nashorn 从JDK 6开始,Java就已经捆绑了JavaScript引擎,该引擎基于Mozilla的Rhino.该特性 ...
- ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存
基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...
- 更简洁的 CSS 清理浮动方式
CSS清理浮动有很多种方式,像使用 br 标签自带的 clear 属,使用元素的 overflow,使用空标签来设置 clear:both 等等.但考虑到兼容问题和语义化的问题,一般我们都会使用如下代 ...
- [译]JDK 6 and JDK 7中的subString()方法
(说明,该文章翻译自The substring() Method in JDK 6 and JDK 7) 在JDK 6 and JDK 7中的substring(int beginIndex, int ...
- 了解JDK 6和JDK 7中substring的原理及区别
substring(int beginIndex, int endIndex)方法在jdk 6和jdk 7中的实现是不同的.了解他们的区别可以帮助你更好的使用他.为简单起见,后文中用substring ...
随机推荐
- java中关于锁知识的整理
1.1什么是锁? 在计算机科学中,锁(lock)或互斥(mutex)是一种同步机制,用于在有许多执行线程的环境中强制对资源的访问限制.锁旨在强制实施互斥排他.并发控制策略. 锁通常需要硬件支持才能有效 ...
- mongodb for windows安装
1,下载mongodb for windwos 下载地址:https://www.mongodb.com/download-center#community 2,创建db和log的文件夹 D:\dat ...
- Android-RemoteView-桌面小部件
Android-RemoteView-桌面小部件 学习自 <Android开发艺术探索> https://developer.android.google.cn/guide/topics/ ...
- Centos 7.4下 部署openstack Queens 计算节点qemu高版本问题
sed -i 's/$contentdir/centos/g' /etc/yum.repos.d/CentOS-QEMU-EV.repo 这样既可正常安装compute服务
- Redis学习笔记(1)- CentOS 6.4 安装Redis
Redis学习笔记(1)- CentOS 6.4 安装Redis 2013.10.13 学习环境 vm 10.1 + 默认.新装的干净 CentOS 6.4 64BIT系统 准备 1 ...
- python3 开发面试题(collections中的Counter)6.7
''' 编写Python脚本,分析xx.log文件,按域名统计访问次数 xx.log文件内容如下: https://www.sogo.com/ale.html https://www.qq.com/3 ...
- C# 实现IDisposable的模式
来自MSDN官方文档:http://msdn.microsoft.com/en-us/library/system.configuration.provider.providercollection. ...
- Bugzilla Error message: couldn't create child process: 720003: index.cgi
two steps is try to fix this issue. 1. Turn off the windowns firewall 2. Register the perl to the sy ...
- NXP LPC18xx LPC43xx OTP ID Boot
static LPC_DEVICE_TYPE LPCtypes[] = { { , , , , , , , , , CHIP_VARIANT_NONE }, /* unknown */ // id, ...
- gitblit.cmd运行自动关闭
前几天运行gitblit.cmd一直正常,今天运行gitblit.cmd,几秒钟后命令行窗口就自动关闭了,导致无法启动gitblit服务器,查看日志如下: 刚开始以为是防火墙问题,在防火墙中添加了程序 ...