AutoCloseable
在jdk1.7中引入,Cloesable
在jdk1.5中已经存在。
并根据https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
The try-with-resources statement ensures that each resource is closed
at the end of the statement. Any object that implements
java.lang.AutoCloseable, which includes all objects which implement
java.io.Closeable, can be used as a resource.
因此,Closeable
实例已经可以在 try-with-resources
语句中被视为资源。这是肯定的,因为 Closeable
从 AutoCloseable
扩展而来。
我的问题是为什么java专门引入了AutoCloseable
,为什么不让Closeable只在try-with-resources
中支持,有没有其他方法除了 try-with-resources
之外,是否可以使用 AutoCloseable?
Closeable
仅限于抛出 IOException
,这可能不适用于某些可关闭但非 IO 绑定(bind)的资源。
AutoCloseable
声明为抛出 Exception
,使其更通用。
Closeable
的 API 不能更改为抛出 Exception
,因为那将是一个重大更改,因此需要新的 super 接口(interface)。
此外,作为 documented :
Note that unlike the close
method of Closeable
, this close method is not required to be idempotent. In other words, calling this close method more than once may have some visible side effect, unlike Closeable.close
which is required to have no effect if called more than once. However, implementers of this interface are strongly encouraged to make their close methods idempotent.
因此,虽然每个 Closeable
都是 Autocloseable
,但反之则不然,将 try-catch-finally 限制为 的语义会受到限制可关闭
。