Java是否有使用声明? [英] Does Java have a using statement?

查看:147
本文介绍了Java是否有使用声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java是否有在hibernate中打开会话时可以使用的using语句?



在C#中,类似于:

  using(var session = new Session())
{


}

所以这个对象会超出范围并自动关闭。

解决方案

Java 7引入了自动资源块管理它将这个功能带到Java平台。以前的Java版本没有类似于使用的任何内容。

例如,您可以使用任何实现变量 java.lang.AutoCloseable 用以下方式:

  try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable())
{
...
}



Java的 java.io.Closeable 接口,由流实现,自动扩展 AutoCloseable ,所以你可以使用在 try >块中的流将以与使用
块的方式在C#中使用它们的方式相同。这相当于C#的使用



version 5.0,Hibernate Sessions实现 AutoCloseable 并且可以在ARM模块中自动关闭。在以前的Hibernate版本中, Session did不执行 AutoCloseable 。因此,您需要使用Hibernate> = 5.0才能使用此功能。


Does Java have a using statement that can be used when opening a session in hibernate?

In C# it is something like:

using (var session = new Session())
{


}

So the object goes out of scope and closes automatically.

解决方案

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.

As an example, you can use any variable implementing java.lang.AutoCloseable in the following way:

try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable())
{
    ...
}

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.

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是否有使用声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆