我有一个非常简单的问题,对我来说似乎很愚蠢但却要求.How BufferedReader调用Autocloseable接口的close()方法。或者我们如何实现自动调用close()的Autocloseable。
答案 0 :(得分:1)
它的语法糖。 javac编译器将close()
调用插入到声明try
的{{1}}块末尾的编译类中,因为您可以看到是否使用{{1来反汇编类文件}}
答案 1 :(得分:0)
除了实现AutoCloseable
之外,您在自己的代码中无需执行任何操作,并提供close()
方法。 Java负责在close()
语句末尾为您调用try
方法。考虑以下最小的演示:
class MyCloseable implements AutoCloseable {
public void close() { System.out.println("Close was called"); }
}
public class Ac {
public static void main(String[] args) {
try (MyCloseable mc = new MyCloseable()) {
}
}
}
$ java Ac
Close was called
答案 2 :(得分:0)
try(AutoClosable x = open()) {}
try {
Resource x = open();
} finally {
x.close();
}
有两个实际差异:
如果两个块都抛出,则autoclosable try
语句将从try
语句中抛出异常,而try...finally
将抛出finally块中的异常。另一个块的例外将被抑制。
此外,确切的行为是这样的:
try(Autoclosable x = open) {
//do something
} do_close {
x.close();//not actually there - executed before catch and finally!
} catch (WhateverException e){
//catch an exception
} finally {
//finally do something
}
来自Oracle Docs:
“try-with-resources语句可以捕获并最终阻塞 像一个普通的尝试声明。在try-with-resources语句中,任何 在声明的资源之后运行catch或finally块 关闭。“
因此,由于这两个技术细节,它不仅仅是语法糖,而且在实践中它被用于原先使用try...finally
的地方。
除了Autoclosable
afaik之外,没有其他方式可以模仿try-with-resources的行为。如果您想在尝试后进行一些清理,则必须使用finally
或实施Autoclosable
。终结者似乎做了类似的事情,但事实上他们没有。我只是在这里提到advise you not to use them。