Java 有 using 语句吗? [英] Does Java have a using statement?
问题描述
Java 有没有可以在 hibernate 中打开会话时使用的 using 语句?
Does Java have a using statement that can be used when opening a session in hibernate?
在 C# 中是这样的:
In C# it is something like:
using (var session = new Session())
{
}
因此对象超出范围并自动关闭.
So the object goes out of scope and closes automatically.
推荐答案
Java 7 引入 自动资源块管理,将这一特性引入到 Java 平台.以前的 Java 版本没有任何类似于 using
的东西.
Java 7 introduced Automatic Resource Block Management which brings this feature to the Java platform. Prior versions of Java didn't have anything resembling using
.
例如,您可以通过以下方式使用任何实现 java.lang.AutoCloseable
的变量:
As an example, you can use any variable implementing java.lang.AutoCloseable
in the following way:
try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable())
{
...
}
Java 的 java.io.Closeable
接口,由流实现,自动扩展 AutoCloseable
,所以你已经可以在 try
块中使用流与在 C# using
块中使用它们的方式相同.这相当于C#的using
.
Java's java.io.Closeable
interface, implemented by streams, automagically extends AutoCloseable
, so you can already use streams in a try
block the same way you would use them in a C# using
block. This is equivalent to C#'s using
.
从 5.0 版开始, Hibernate Sessions 实现 AutoCloseable
并且可以在 ARM 块中自动关闭.在以前版本的 Hibernate Session 中不实现 AutoCloseable
.因此,您需要使用 Hibernate >= 5.0 才能使用此功能.
As of version 5.0, Hibernate Sessions implement AutoCloseable
and can be auto-closed in ARM blocks. In previous versions of Hibernate Session did not implement AutoCloseable
. So you'll need to be on Hibernate >= 5.0 in order to use this feature.
这篇关于Java 有 using 语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!