任何继承了Closeable或者AutoCloseable的类(Closeable接口继承自AutoCloseable接口),都可以放在try-with-resource里使用,以便在try块结束的时候自动释放资源close;
jdk9之前的try-with-resource需要在try的括号里新建变量,jdk9更便捷,可以直接使用try之前的变量;
demo:
package test;
public class MainTest {
public static void main(String[] args) {
try (Abc abc = new Abc()) {
abc.test();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
//jdk9可以直接使用已经存在的变量
Abc abc2 = new Abc();
try(abc2){
abc2.test();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally2");
}
}
}
class Abc implements AutoCloseable{
public void test() {
System.out.println("Abc test()");
}
@Override
public void close() throws Exception {
System.out.println("Abc close()");
}
}
结果: