Java try-with-resources 结构不仅适用于 Java 内置类。您也可以在自己的类中实现 java.lang.AutoCloseable 接口,并将它们与 try-with-resources 构造一起使用。
AutoClosable 接口只有一个名为 close() 的方法。下图是该接口的定义:

任何实现该接口的类都可以使用 Java try-with-resources 结构。下面是一个简单的实现示例:
package com.hxstrive.jdk7.try_with_resources;
/**
* JDK7 新特性 try-with-resources
* @author hxstrive.com
*/
public class TryWithResourcesDemo3 {
static class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("close");
}
public void doSomething() {
System.out.println("doSomething");
}
}
public static void main(String[] args) throws Exception {
// 这里在 try-with-resources 中使用 MyResource 资源
try (MyResource resource = new MyResource()) {
resource.doSomething();
}
//结果:
//doSomething
//close
}
}MyResource 中的 doSomething() 方法并不是 AutoClosable 接口的一部分。它之所以存在,是因为我们希望除了关闭对象外,还能执行其他操作。
正如您所看到的,try-with-resources 是一种相当强大的方法,可以确保 try-catch 块内使用的资源被正确关闭,无论这些资源是您自己创建的,还是 Java 内置的组件。