1、try-with-resources的用法
jdk1.7引入了一个语法叫 try-with-resource语法,它的使用如下:
如果一个类实现了 AutoCloseable 接口,并行重写 close 方法。那么这个类就可以写在try-catch的try后面的括号中,并且能在try-catch块执行后自动执行这个方法。
举例如下:
public class TryWithResource implements AutoCloseable {
private int age = 18;
@Override
public void close() throws Exception {
System.out.println("this is close 方法");
}
public static void main(String[] args) {
try (TryWithResource tryWithResource = new TryWithResource()) {
System.out.println(tryWithResource.age);
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行这个方法,我们看到打印结果:
18
this is close 方法
很明显这样写和下面这种经典写法的效果是一样的,只是看上去能更加简便一些。
public class TryWithResource{
private int age = 18;
public void close() throws