Java7 AutoCloseable入门实例教程



Java7 AutoCloseable入门实例教程。AutoCloseable接口,表示一种不再使用时需要关闭的资源。这个接口下只有一个方法,close()。这个方法在try-with- resource语法下会被自动调用,支持抛出Exception,当然它也鼓励抛出更详细的异常。close()建议不要抛出线程中断的 InterruptedException。对这个接口的实现,规范强烈建议close()是幂等的,也就是说多次调用close()方法和一次调用的结 果是一样的。

AutoCloseable的简单实现:

public class MyResource implements AutoCloseable {

@Override
public void close() throws Exception {
System.out.println(“Close resource!”);
}

public void readResource() {
System.out.println(“Read resource!”);
}

}
try-resource单元测试:

@Test
public void testCloseResource() throws Exception {
try(MyResource autoCloseable = new MyResource()) {
autoCloseable.readResource();
}
}
输出结果:
Read resource!
Close resource!