在 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 ...
随机推荐
- sqlite读写
#coding=utf-8 import sqlite3 import os #创建数据库和游标 if os.path.exists(' test.db'): conn=sqlite3.connect ...
- 那些年我们踩过的坑之表单reset
开发者往往是在一个又一个的坑中成长起来的,自学的开发者尤其如此,刚刚填完一个坑,转身又掉进另一个坑.有些坑很容易就跳出来了,也有些坑能整了一天都没头绪,第二天早上一来发现后面就有一架通往坑外的梯子,坑 ...
- BZOJ.1007.[HNOI2008]水平可见直线(凸壳 单调栈)
题目链接 可以看出我们是要维护一个下凸壳. 先对斜率从小到大排序.斜率最大.最小的直线是一定会保留的,因为这是凸壳最边上的两段. 维护一个单调栈,栈中为当前可见直线(按照斜率排序). 当加入一条直线l ...
- NOIP练习赛题目1
有些题目可能没做,如计算几何.恶心模拟. 高级打字机 难度级别:C: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 早苗入手了最新的高级打字机 ...
- Codeforces Round #370 (Div. 2) C. Memory and De-Evolution 水题
C. Memory and De-Evolution 题目连接: http://codeforces.com/contest/712/problem/C Description Memory is n ...
- Codeforces Beta Round #14 (Div. 2) A. Letter 水题
A. Letter 题目连接: http://www.codeforces.com/contest/14/problem/A Description A boy Bob likes to draw. ...
- 使用Python中的HTMLParser、cookielib抓取和解析网页、从HTML文档中提取链接、图像、文本、Cookies(二)(转)
对搜索引擎.文件索引.文档转换.数据检索.站点备份或迁移等应用程序来说,经常用到对网页(即HTML文件)的解析处理.事实上,通过 Python语言提供的各种模块,我们无需借助Web服务器或者Web浏览 ...
- Mac的brew和brew cask区别以及安装brew cask
brew多用于命令行. brew cask主要用于有GUI的软件,例如VLC等等. brew cask是brew的一个子集,也就是一个扩展. 安装brew cask扩展: ruby -e " ...
- Training JTAG Interface
For most embedded CPU architecture implementations, the JTAG port is used by the debugger to interfa ...
- sqlserver 2012 IDE中 Windows身份验证连接服务器报错 ,Login failed for user 'xxx\Administrator'. 原因: 找不到与提供的名称匹配的登录名。
问题描述: 本地装了两个实例,一个是SQLEXPRESS,可以正常操作.但是另一个开发常用的实例MSSQLSERVER却连Windows身份验证都报错,报的错误也是很奇葩,怎么会找不到Administ ...