在Java7中,引入了一个新特性try-with-resource,即在try中的代码,其资源会自动释放,不用手工执行资源释放操作。
要求跟在try后面的资源必须实现AutoCloseable接口,否则会报变异错误,代码示例如下:
class CustomResource implements AutoCloseable
{
@Override
public void close() throws Exception {
System.out.println("进行资源释放操作!");
}
public static void main(String[] args) throws Exception {
try(CustomResource r = new CustomResource()) {
System.out.println("使用资源!");
}
}
}