Java 有 using 语句吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2016299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:36:30  来源:igfitidea点击:

Does Java have a using statement?

javahibernateusing-statement

提问by mrblah

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

Java 是否有可以在休眠状态下打开会话时使用的 using 语句?

In C# it is something like:

在 C# 中,它类似于:

using (var session = new Session())
{


}

So the object goes out of scope and closes automatically.

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

采纳答案by Asaph

Java 7 introduced Automatic Resource Block Managementwhich brings this feature to the Java platform. Prior versions of Java didn't have anything resembling using.

Java 7 引入了自动资源块管理,将这一特性引入了 Java 平台。以前的 Java 版本没有任何类似于using.

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

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

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

Java's java.io.Closeableinterface, implemented by streams, automagically extends AutoCloseable, so you can already use streams in a tryblock the same way you would use them in a C# usingblock. This is equivalent to C#'s using.

Java 的java.io.Closeable接口由流实现,自动扩展AutoCloseable,因此您已经可以在try块中使用流,就像在 C#using块中使用流一样。这相当于 C# 的using.

As of version 5.0, Hibernate Sessions implement AutoCloseableand 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.

5.0 版开始,Hibernate Sessions 实现AutoCloseable并可以在 ARM 块中自动关闭。在以前版本的 Hibernate Session 中没有实现AutoCloseable. 因此,您需要使用 Hibernate >= 5.0 才能使用此功能。

回答by Rich Adams

No, Java has no usingstatement equivalent.

不,Java 没有using等效的语句。

回答by ChaosPandion

Technically:

技术上:

DisposableObject d = null;
try {
    d = new DisposableObject(); 
}
finally {
    if (d != null) {
        d.Dispose();
    }
}

回答by missingfaktor

As of now, no.

截至目前,没有。

However there is a proposal of ARMfor Java 7.

然而,有一个针对 Java 7的ARM提案。

回答by Joachim Sauer

Before Java 7, there was nosuch feature in Java (for Java 7 and up see Asaph's answerregarding ARM).

在 Java 7 之前,Java没有这样的功能(对于 Java 7 及更高版本,请参阅AsaphARM的回答)。

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 codenor hooray.close()can throw any exceptions.

这就是既不能// Great codehooray.close()不能抛出任何异常的代码。

If you reallyonly 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.

但这可能不是你的意思。

回答by Michael Borgwardt

The closest java equivalent is

最接近的 java 等价物是

AwesomeClass hooray = new AwesomeClass();
try{
    // Great code
} finally {
    hooray.dispose(); // or .close(), etc.
}

回答by Will Marcouiller

Please see this List of Java Keywords.

请参阅此Java 关键字列表

  1. The usingkeyword is unfortunately not part of the list.
  2. And there is also no equivalence of the C# usingkeyword through any other keyword as for now in Java.
  1. using不幸的是,关键字不是列表的一部分。
  2. 并且using目前在 Java 中也没有 C#关键字通过任何其他关键字的等效项。

To imitate such "using"behaviour, you will have to use a try...catch...finallyblock, where you would dispose of the resources within finally.

要模仿这种"using"行为,您必须使用一个try...catch...finally块,您可以在其中处理finally.

回答by krock

ARM blocks, from project coinwill be in Java 7. This is feature is intended to bring similar functionality to Java as the .Net using syntax.

ARM 块,来自项目代币将在 Java 7 中。此功能旨在为 Java 带来与使用语法的 .Net 类似的功能。

回答by Adam Paynter

If you're interested in resource management, Project Lombokoffers the @Cleanupannotation. Taken directly from their site:

如果您对资源管理感兴趣,Project Lombok 会提供@Cleanup注释。直接取自他们的网站:

You can use @Cleanupto ensure a given resource is automatically cleaned up before the code execution path exits your current scope. You do this by annotating any local variable declaration with the @Cleanupannotation like so:

@Cleanup InputStream in = new FileInputStream("some/file");

As a result, at the end of the scope you're in, in.close()is called. This call is guaranteed to run by way of a try/finally construct. Look at the example below to see how this works.

If the type of object you'd like to cleanup does not have a close()method, but some other no-argument method, you can specify the name of this method like so:

@Cleanup("dispose") org.eclipse.swt.widgets.CoolBar bar = new CoolBar(parent, 0);

By default, the cleanup method is presumed to be close(). A cleanup method that takes argument cannot be called via @Cleanup.

您可以使用@Cleanup确保在代码执行路径退出当前范围之前自动清理给定资源。您可以通过使用注释对任何局部变量声明进行@Cleanup注释来做到这一点,如下所示:

@Cleanup InputStream in = new FileInputStream("some/file");

结果,在您所在范围的末尾,in.close()被调用。此调用保证通过 try/finally 构造运行。看看下面的例子,看看它是如何工作的。

如果您要清理的对象类型没有close()方法,但有其他一些无参数方法,您可以指定此方法的名称,如下所示:

@Cleanup("dispose") org.eclipse.swt.widgets.CoolBar bar = new CoolBar(parent, 0);

默认情况下,清理方法假定为 close(). 不能通过 调用带有参数的清理方法 @Cleanup

Vanilla Java

香草爪哇

import java.io.*;

public class CleanupExample {
  public static void main(String[] args) throws IOException {
    InputStream in = new FileInputStream(args[0]);
    try {
      OutputStream out = new FileOutputStream(args[1]);
      try {
        byte[] b = new byte[10000];
        while (true) {
          int r = in.read(b);
          if (r == -1) break;
          out.write(b, 0, r);
        }
      } finally {
        out.close();
      }
    } finally {
      in.close();
    }
  }
}

With Lombok

与龙目岛

import lombok.Cleanup;
import java.io.*;

public class CleanupExample {
  public static void main(String[] args) throws IOException {
    @Cleanup InputStream in = new FileInputStream(args[0]);
    @Cleanup OutputStream out = new FileOutputStream(args[1]);
    byte[] b = new byte[10000];
    while (true) {
      int r = in.read(b);
      if (r == -1) break;
      out.write(b, 0, r);
    }
  }
}

回答by riwi

Since Java 7 it does: http://blogs.oracle.com/darcy/entry/project_coin_updated_arm_spec

从 Java 7 开始:http: //blogs.oracle.com/darcy/entry/project_coin_updated_arm_spec

The syntax for the code in the question would be:

问题中代码的语法是:

try (Session session = new Session())
{
  // do stuff
}

Note that Sessionneeds to implement AutoClosableor one of its (many) sub-interfaces.

请注意,Session需要实现AutoClosable其(许多)子接口之一。