try-with-resources语句

来源:互联网 发布:python pillow 安装 编辑:程序博客网 时间:2024/06/07 01:56

传统的try catch finally 使用场景有 io流关闭,数据库连接池关闭等。
Java SE7新特性出来个try-with-resources,可以省略finally方法。
先直接上代码吧

TestTryWithResouce.java

@Slf4jpublic class TestTryWithResouce {    @Test    public void test() {        try (Pool pool = new Pool()) {            pool.get();            Integer.parseInt("ddd");        } catch (Exception e) {            log.error(e.getLocalizedMessage());        }    }}

Pool .java

@Slf4jpublic class Pool implements AutoCloseable {    public void close() {        log.info("pool回收");    }    public Object get() {        log.info("得到对象");        return null;    }}

输出结果:

2015-09-15 11:01:47,211 INFO [main] (Pool.java:12) - 得到对象
2015-09-15 11:01:47,240 INFO [main] (Pool.java:8) - pool回收
2015-09-15 11:01:47,240 ERROR [main] (TestTryWithResouce.java:15) - For input string: “ddd”

使用try with resources 等于将以前的finally里面的方法 放到try()里面去了,try里面多了一个(),pool类实现了AutoCloseable ,实现了接口里面colse()方法

0 0