类可以在不实现 AutoCloseable 接口的情况下支持 try-with-resources 吗?

Aad*_*rma 0 java

我发现try-with-resources可用于任何实现该AutoCloseable接口的类。

public interface AutoCloseable {
  void close() throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

这是类在 Java 中支持try-with-resources的唯一标准吗(我的意思是,是否存在类实现AutoCloseable接口但支持try-with-resources 的可能场景)?

Sla*_*law 5

来自Java语言规范的\xc2\xa714.20.3

\n
\n

在资源规范中声明或引用为资源的变量的类型必须是以下类型的子类型AutoCloseable,否则会发生编译时错误。

\n
\n

换句话说,只有实例AutoCloseable可以与 try-with-resources 一起使用。

\n
\n

术语注释(也在 JLS 的同一部分中进行了解释)。如果你有:

\n
try (AutoCloseable foo = ...;\n     AutoCloseable bar = ...) {\n  // do stuff...\n} catch (Exception ex) {\n  // handle exception...\n}\n
Run Code Online (Sandbox Code Playgroud)\n

那么“资源规范”就是:

\n
(AutoCloseable foo = ...;\n AutoCloseable bar = ...)\n
Run Code Online (Sandbox Code Playgroud)\n

有两个“资源”:foobar

\n