Does Java have a using statement?

前端 未结 12 1978
梦谈多话
梦谈多话 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 16:48

    Before Java 7, there was no such feature in Java (for Java 7 and up see Asaph's answer regarding ARM).

    You needed to do it manually and it was a pain:

    AwesomeClass hooray = null;
    try {
      hooray = new AwesomeClass();
      // Great code
    } finally {
      if (hooray!=null) {
        hooray.close();
      }
    }
    

    And that's just the code when neither // Great code nor hooray.close() can throw any exceptions.

    If you really only want to limit the scope of a variable, then a simple code block does the job:

    {
      AwesomeClass hooray = new AwesomeClass();
      // Great code
    }
    

    But that's probably not what you meant.

提交回复
热议问题