Java有using语句吗?

发布于 2024-09-03 18:46:00 字数 155 浏览 5 评论 0原文

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

在 C# 中,它类似于:

using (var session = new Session())
{


}

因此对象超出范围并自动关闭。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

嘿看小鸭子会跑 2024-09-10 18:46:00

Java 7 引入了自动资源块管理,将此功能引入了 Java 平台。 Java 的早期版本没有类似 using 的内容。

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

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

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

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

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.

百善笑为先 2024-09-10 18:46:00

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

您需要手动执行此操作,这很痛苦

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

这就是当 // Great codehooray.close() 都不是时的代码可以抛出任何异常。

如果您真的只想限制变量的范围,那么一个简单的代码块就可以完成这项工作:

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

但这可能不是您的意思。

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.

嗼ふ静 2024-09-10 18:46:00

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

问题中代码的语法为:

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

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

Since Java 7 it does: 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 Session needs to implement AutoClosable or one of its (many) sub-interfaces.

不…忘初心 2024-09-10 18:46:00

技术上:

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

Technically:

DisposableObject d = null;
try {
    d = new DisposableObject(); 
}
finally {
    if (d != null) {
        d.Dispose();
    }
}
十二 2024-09-10 18:46:00

最接近的java等效项是

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

The closest java equivalent is

AwesomeClass hooray = new AwesomeClass();
try{
    // Great code
} finally {
    hooray.dispose(); // or .close(), etc.
}
戈亓 2024-09-10 18:46:00

截至目前,没有。

然而,有一个 ARM 的提案Java 7.

As of now, no.

However there is a proposal of ARM for Java 7.

感受沵的脚步 2024-09-10 18:46:00

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

您可以使用@Cleanup来确保给定的
资源自动清理
在代码执行路径退出之前
您当前的范围。你这样做是通过
注释任何局部变量
使用 @Cleanup 进行声明
像这样的注释:

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

作为
结果,在你的范围结束时
在中,in.close() 被调用。这个电话是
保证通过a方式运行
尝试/最终构建。看看
下面的例子看看它是如何工作的。

如果您想要的对象类型
cleanup 没有 close()
方法,但还有其他一些无参数的方法
方法,您可以指定名称
这个方法就像这样:

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

默认情况下,清理方法被假定为
关闭()。一种清理方法,需要
参数不能通过调用
@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();
    }
  }
}

使用 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);
    }
  }
}

If you're interested in resource management, Project Lombok offers the @Cleanup annotation. Taken directly from their site:

You can use @Cleanup to 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 @Cleanup
annotation 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.

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);
    }
  }
}
黯然 2024-09-10 18:46:00

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

No, Java has no using statement equivalent.

风尘浪孓 2024-09-10 18:46:00

请参阅此Java 关键字列表

  1. 遗憾的是 using 关键字不在列表中。
  2. 而且目前在 Java 中,C# using 关键字与任何其他关键字之间也不存在等价关系。

要模仿这种“using”行为,您必须使用 try...catch...finally 块,您可以在其中处理 中的资源最后

Please see this List of Java Keywords.

  1. The using keyword is unfortunately not part of the list.
  2. And there is also no equivalence of the C# using keyword through any other keyword as for now in Java.

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

微暖i 2024-09-10 18:46:00

ARM 块,来自 project coin 将出现在 Java 7 中。此功能旨在为 Java 带来与 . Net 使用语法。

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

小矜持 2024-09-10 18:46:00

回答有关限制变量范围的问题,而不是谈论自动关闭/处置变量。

在 Java 中,您可以使用大括号定义封闭的匿名作用域。这非常简单。

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

变量hooray仅在此范围内可用,而在其之外则不可用。

如果您有临时的重复变量,这可能很有用。

例如,每个都有索引。就像 item 变量在 for 循环中封闭(即仅在循环内部可用)一样,index 变量在匿名作用域中封闭。

// first loop
{
    Integer index = -1;
    for (Object item : things) {index += 1;
        // ... item, index
    }
}

// second loop
{
    Integer index = -1;
    for (Object item : stuff) {index += 1;
        // ... item, index
    }
}

如果您没有 for 循环来提供变量范围,但您想使用通用变量名称,有时我也会使用它。

{
    User user = new User();
    user.setId(0);
    user.setName("Andy Green");
    user.setEmail("[email protected]");
    users.add(user);
}

{
    User user = new User();
    user.setId(1);
    user.setName("Rachel Blue");
    user.setEmail("[email protected]");
    users.add(user);
}

To answer the question regarding limiting scope of a variable, instead of talking about automatically closing/disposing variables.

In Java you can define closed, anonymous scopes using curly brackets. It's extremely simple.

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

The variable hooray is only available in this scope, and not outside it.

This can be useful if you have repeating variables which are only temporary.

For example, each with index. Just like the item variable is closed over the for loop (i.e., is only available inside it), the index variable is closed over the anonymous scope.

// first loop
{
    Integer index = -1;
    for (Object item : things) {index += 1;
        // ... item, index
    }
}

// second loop
{
    Integer index = -1;
    for (Object item : stuff) {index += 1;
        // ... item, index
    }
}

I also use this sometimes if you don't have a for loop to provide variable scope, but you want to use generic variable names.

{
    User user = new User();
    user.setId(0);
    user.setName("Andy Green");
    user.setEmail("[email protected]");
    users.add(user);
}

{
    User user = new User();
    user.setId(1);
    user.setName("Rachel Blue");
    user.setEmail("[email protected]");
    users.add(user);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文