Java 一次性模式
C# 支持使用 处置模式进行确定性垃圾收集的一次性模式。
java有这样的模式吗?
Java 7 具有 自动关闭
,您可以将其与 try finally 块一起使用来调用 close
方法。
7 之前的版本怎么样?
Java 5 或 6 是否有一次性模式(确定性垃圾收集)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 7 之前最接近的只是“手动”try/finally 块:
当我第一次从 Java 背景开始使用 C# 1.0 时,
using
语句是我发现 C# 最好的东西之一。很高兴最终在 Java 7 中看到它:)您还应该考虑
Closeables
- 它使您不必担心引用是否为 null(就像using
语句一样)做)和可选“记录并吞下”关闭时引发的异常,以避免任何此类异常有效地“覆盖”从 try 块引发的异常。The closest prior to Java 7 is just "manual" try/finally blocks:
The
using
statement was one of the things I found nicest about C# when I first started using C# 1.0 from a Java background. It's good to see it finally in Java 7 :)You should also consider
Closeables
in Guava - it allows you to not worry about whether or not a reference is null (just like ausing
statement does) and optionally "logs and swallows" exceptions thrown when closing, to avoid any such exception from effectively "overwriting" an exception thrown from the try block.处置模式的全部目的是支持 C# 独特的
using (temporaryObject)
模式。 Java 在 7 之前没有类似的模式。所有拥有资源的 Java 对象都支持通过手动关闭持有资源的对象来处理模式。
The entire purpose of the disposal pattern is to support C#'s unique
using (temporaryObject)
pattern. Java has had nothing like that pattern before 7.All Java objects that had resources supported the disposal pattern via manually closing the object that held resources.
您正在寻找的是尝试资源。
当然,资源必须是可关闭的(或自动关闭的)。
What you are looking for is try with resources.
The resource has to be Closeable (or AutoCloseable), of course.