我发现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 的可能场景)?
\n\n在资源规范中声明或引用为资源的变量的类型必须是以下类型的子类型
\nAutoCloseable,否则会发生编译时错误。
换句话说,只有实例AutoCloseable可以与 try-with-resources 一起使用。
术语注释(也在 JLS 的同一部分中进行了解释)。如果你有:
\ntry (AutoCloseable foo = ...;\n AutoCloseable bar = ...) {\n // do stuff...\n} catch (Exception ex) {\n // handle exception...\n}\nRun Code Online (Sandbox Code Playgroud)\n那么“资源规范”就是:
\n(AutoCloseable foo = ...;\n AutoCloseable bar = ...)\nRun Code Online (Sandbox Code Playgroud)\n有两个“资源”:foo和bar。