jdk 1.7 新增类AutoCloseable
我们来看看源(蹩)码(脚)中(的)的(翻)注(译)释
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public interface AutoCloseable {
void close() throws Exception; }
|
我们来看下具体的demo
AutoCloseableBean
1 2 3 4 5 6 7 8 9 10 11 12
| package com.java.io;
public class AutoCloseableBean implements AutoCloseable { @Override public void close() throws Exception { System.out.println(this.getClass().getName() + ":close");
} }
|
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.java.io;
public class AutoCloseableDemo {
public static void main(String[] args) { try(AutoCloseableBean autoCloseableBean = new AutoCloseableBean()) { System.out.println("autoCloseableBean init"); throw new Exception("error"); } catch (Exception e) { e.printStackTrace(); System.out.println("catch exception"); } finally { System.out.println("finally"); } }
}
|
运行的结果
1 2 3 4
| autoCloseableBean init com.java.io.AutoCloseableBean:close catch exception finally
|
我们可以看到AutoCloseableBean实现了AutoCloseable的close方法,并打印close
从运行结果可以看到不管try中语句是正常的执行还是有异常,最终AutoCloseableBean会在catch、finally之前执行关闭