try with resource的错误用法
今天review一个老项目的代码,发现一些使用 try with resource 的错误使用,记录一下。
使用方法
try with resource 使用时,会按变量定义顺序,倒序关闭对象,但是,需注意,这里的多个对象,都需要明确的定义,如下:
代码示例
实际代码就不展示了,自己写了一个小例子来记录。
- 先定义两个类
public class Person implements AutoCloseable{
public Person() {
System.out.println("Person init");
}
@Override
public void close() throws Exception {
System.out.println("Person close");
}
}
public class Child implements AutoCloseable{
public Child() {
System.out.println("Child init");
}
public Child(Person p) {
System.out.println("Child init with Person");
}
@Override
public void close() throws Exception {
System.out.println("Child close");
}
}
- 错误使用
public class Test {
public static void main(String[] args) {
try (Child c = new Child(new Person())) {
System.out.println("try with resource");
} catch(Exception e) {
e.printStackTrace();
}
}
}
以上代码运行结果:
3. 正确使用
public class Test {
public static void main(String[] args) {
try (Person p = new Person();
Child c = new Child(p)) {
System.out.println("try with resource");
} catch(Exception e) {
e.printStackTrace();
}
}
}
以上代码运行结果: