简体   繁体   English

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

[英]Can a class support try-with-resources without implementing AutoCloseable interface?

I see that try-with-resources is available to any class that implements the AutoCloseable interface.我看到任何实现AutoCloseable接口的 class 都可以使用try-with-resources

public interface AutoCloseable {
  void close() throws Exception;
}

Is that the only criteria for a class to support try-with-resources in Java (I meant, are there any possible scenarios where a class doesn't implement AutoCloseable interface but supports try-with-resources )?这是 class 支持 Java 中资源尝试的唯一标准吗(我的意思是,是否存在 class 不支持尝试资源AutoCloseable关闭任何可能场景)?

From §14.20.3 of the Java Language Specification :来自Java 语言规范的第 14.20.3 节

The type of a variable declared or referred to as a resource in a resource specification must be a subtype of AutoCloseable , or a compile-time error occurs.在资源规范中声明或引用为资源的变量的类型必须是AutoCloseable的子类型,否则会发生编译时错误。

In other words, only instances of AutoCloseable can be used with try-with-resources.换句话说,只有AutoCloseable的实例可以与 try-with-resources 一起使用。


Note on terminology (also explained in the same section of the JLS).关于术语的注释(也在 JLS 的同一部分中进行了解释)。 If you have:如果你有:

try (AutoCloseable foo = ...;
     AutoCloseable bar = ...) {
  // do stuff...
} catch (Exception ex) {
  // handle exception...
}

Then the "resource specification" is:那么“资源规范”就是:

(AutoCloseable foo = ...;
 AutoCloseable bar = ...)

And there are two "resources": foo and bar .并且有两个“资源”: foobar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM