java8:try-with-resources

java8:try-with-resources

在try( …)里声明的资源,会在try-catch代码块结束后自动关闭掉

public class Trys {
    private static void testAutoClose() {
        AutoCloseable globalObj1 = null;
        AutoCloseable globalObj2 = null;
        try (
                AutoCloseable obj1 = new AutoClosedImpl("obj1");
                AutoCloseable obj2 = new AutoClosedImpl("obj2");
        ) {
            globalObj1 = obj1;
            int i = 1 / 0;
            globalObj2 = obj2;
            System.out.println("finished");
        } catch (Exception e) {
            System.out.println("no finished");
            e.printStackTrace();
        } finally {
            try {
                System.out.println("before finally close");
                if (globalObj1 != null) {
                    globalObj1.close();
                }
                if (globalObj2 != null) {
                    globalObj2.close();
                }
                System.out.println("after finally close");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static class AutoClosedImpl implements AutoCloseable {
        private String name;

        AutoClosedImpl(String name) {
            this.name = name;
        }

        @Override
        public void close() throws Exception {
            System.out.println(name + " closing");
        }
    }

    public static void main(String[] args) {
        testAutoClose();
    }

}

结果:

  1. 凡是实现了AutoCloseable接口的类,在try()里声明该类实例的时候,在try结束后,close方法都会被调用
  2. catch 块中,看不到 try-with-recourse 声明中的变量。
  3. try结束后自动调用的close方法,这个动作会早于catch代码块的执行,也早于finally里调用的方法。
  4. 不管是否出现异常(int i=1/0会抛出异常),try()里的实例都会被调用close方法
  5. 越晚声明的对象,会越早被close掉。

你可能感兴趣的:(java)