Does Java have a using statement?

前端 未结 12 1976
梦谈多话
梦谈多话 2020-11-28 16:13

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()         


        
12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 17:01

    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.

提交回复
热议问题