java 是否有等效于 C# 的“using”子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/141241/
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
Does java have an equivalent to the C# "using" clause
提问by dacracot
I've seen reference in some C# posted questions to a "using" clause. Does java have the equivalent?
我在一些 C# 发布的问题中看到了对“使用”子句的引用。java有等价的吗?
回答by Aaron Maenpaa
Yes. Java 1.7 introduced the try-with-resourcesconstruct allowing you to write:
是的。Java 1.7 引入了try-with-resources构造,允许您编写:
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
... just like a usingstatement.
...就像一个using声明。
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
不幸的是,在 Java 1.7 之前,Java 程序员被迫使用 try{ ... } finally { ... }。在 Java 1.6 中:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is 2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
回答by Lodewijk Bogaards
Yes, since Java 7 you can rewrite:
是的,从 Java 7 开始,您可以重写:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
As
作为
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
The objects passed as parameters to the try statement should implement java.lang.AutoCloseable.Have a look at the official docs.
作为参数传递给 try 语句的对象应该实现java.lang.AutoCloseable。查看官方文档。
For older versions of Java checkout this answerand this answer.
回答by Tom Hawtin - tackline
The nearest equivalent within the language is to use try-finally.
该语言中最接近的等价物是使用 try-finally。
using (InputStream in as FileInputStream("myfile")) {
... use in ...
}
becomes
变成
final InputStream in = FileInputStream("myfile");
try {
... use in ...
} finally {
in.close();
}
Note the general form is always:
请注意,一般形式始终为:
acquire;
try {
use;
} finally {
release;
}
If acquisition is within the try block, you will release in the case that the acquisition fails. In some cases you might be able to hack around with unnecessary code (typically testing for null in the above example), but in the case of, say, ReentrantLock bad things will happen.
如果获取在try块内,则在获取失败的情况下释放。在某些情况下,您可能会使用不必要的代码进行破解(通常在上面的示例中测试 null),但是在例如 ReentrantLock 的情况下,会发生不好的事情。
If you're doing the same thing often, you can use the "execute around" idiom. Unfortunately Java's syntax is verbose, so there is a lot of bolier plate.
如果你经常做同样的事情,你可以使用“execute around”这个习语。不幸的是,Java 的语法很冗长,所以有很多板子。
fileInput("myfile", new FileInput<Void>() {
public Void read(InputStream in) throws IOException {
... use in ...
return null;
}
});
where
在哪里
public static <T> T fileInput(FileInput<T> handler) throws IOException {
final InputStream in = FileInputStream("myfile");
try {
handler.read(in);
} finally {
in.close();
}
}
More complicated example my, for instance, wrap exceptions.
更复杂的例子我,例如,包装异常。
回答by Tim
It was a long time coming but with Java 7 the try-with-resources statementwas added, along with the AutoCloseableinterface.
这是一个很长的时间,但是在 Java 7 中添加了try-with-resources 语句以及AutoCloseable接口。
回答by McDowell
The closest you can get in Java is try/finally. Also, Java does not provide an implicit Disposable type.
在 Java 中最接近的是 try/finally。此外,Java 不提供隐式 Disposable 类型。
C#: scoping the variable outside a using block
C#:在 using 块之外确定变量的范围
public class X : System.IDisposable {
public void Dispose() {
System.Console.WriteLine("dispose");
}
private static void Demo() {
X x = new X();
using(x) {
int i = 1;
i = i/0;
}
}
public static void Main(System.String[] args) {
try {
Demo();
} catch (System.DivideByZeroException) {}
}
}
Java: scoping the variable outside a block
Java:将变量范围限定在块外
public class X {
public void dispose() {
System.out.println("dispose");
}
private static void demo() {
X x = new X();
try {
int i = 1 / 0;
} finally {
x.dispose();
}
}
public static void main(String[] args) {
try {
demo();
} catch(ArithmeticException e) {}
}
}
C#: scoping the variable inside a block
C#:在块内确定变量的范围
public class X : System.IDisposable {
public void Dispose() {
System.Console.WriteLine("dispose");
}
private static void Demo() {
using(X x = new X()) {
int i = 1;
i = i/0;
}
}
public static void Main(System.String[] args) {
try {
Demo();
} catch (System.DivideByZeroException) {}
}
}
Java: scoping the variable inside a block
Java:在块内确定变量的范围
public class X {
public void dispose() {
System.out.println("dispose");
}
private static void demo() {
{
X x = new X();
try {
int i = 1 / 0;
} finally {
x.dispose();
}
}
}
public static void main(String[] args) {
try {
demo();
} catch(ArithmeticException e) {}
}
}
回答by Bob King
Not that I'm aware of. You can somewhat simulate with a try...finally block, but it's still not quite the same.
不是我所知道的。您可以使用 try...finally 块进行模拟,但它仍然不完全相同。
回答by Pablo Fernandez
I think you can achieve something similar to the "using" block, implementing an anonymous inner class. Like Spring does with the "Dao Templates".
我认为你可以实现类似于“使用”块的东西,实现一个匿名内部类。就像 Spring 对“Dao 模板”所做的那样。
回答by Andrei R?nea
Well, using was syntactic sugar anyway so Java fellows, don't sweat it.
好吧,无论如何使用是语法糖,所以 Java 伙伴,不要担心。
回答by Lars Westergren
If we get BGGA closures in Java, this would also open up for similar structures in Java. Gafter has used this example in his slides, for example:
如果我们在 Java 中获得 BGGA 闭包,这也将为 Java 中的类似结构打开。Gafter 在他的幻灯片中使用了这个例子,例如:
withLock(lock) { //closure }
回答by Lars Westergren
The actual idiom used by most programmers for the first example is this:
大多数程序员在第一个例子中使用的实际习语是这样的:
InputStream is1 = null;
InputStream is2 = null;
try{
is1 = new FileInputStream("/tmp/bar");
is2 = new FileInputStream("/tmp/foo");
/* do stuff with is1 and is 2 */
} finally {
if (is1 != null) {
is1.close();
}
if (is2 != null) {
is2.close();
}
}
There is less indenting using this idiom, which becomes even more important when you have more then 2 resources to cleanup.
使用此习语的缩进较少,当您需要清理超过 2 个资源时,缩进变得更加重要。
Also, you can add a catch clause to the structure that will deal with the new FileStream()'s throwing an exception if you need it to. In the first example you would have to have another enclosing try/catch block if you wanted to do this.
此外,如果需要,您可以向结构中添加一个 catch 子句,该子句将处理 new FileStream() 引发的异常。在第一个示例中,如果您想这样做,您必须有另一个封闭的 try/catch 块。

