try-with-resources语句

2018-07-12  本文已影响0人  norvid

Java中原来对于资源类的处理,习惯于使用try-finally的方式在finally块中关闭资源。

public class Releasable {
    public void close() {
        System.out.println("release!");
    }

    public static void main(String[] args) {
        Releasable robj = null;
        try {
            robj = new Releasable();
            System.out.println("doing!");
        } finally {
            // 资源在finally块中显式关闭
            robj.close();
        }
        System.out.println("done!");
    }
}

从JDK7开始,引入了AutoCloseable接口和try-with-resources语句,只要资源类继承了AutoCloseable,就可以不再显式地关闭资源。JVM自动完成资源的释放。

public class Releasable implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("release!");
    }

    public static void main(String[] args) {
        // 在try中创建对象,在try块结束时自动调用close()来释放。
        try (Releasable robj = new Releasable()) {
            System.out.println("doing!");
        }
        System.out.println("done!");
    }
}

以上两段代码的输出结果都是:

doing!
release!
done!

————(完)————

上一篇 下一篇

猜你喜欢

热点阅读