java 是否具有与 C# “using” 子句等效的

2022-09-01 17:06:01

我看到一些C#发布的问题引用了“using”子句。Java有等价物吗?


答案 1

是的。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 */
}

...就像一个声明。using

不幸的是,在Java 1.7之前,Java程序员被迫使用try{ ... } 最后{ ... }。在 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();
}

答案 2

是的,从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();
}

try(InputStream is1 = new FileInputStream("/tmp/foo");
    InputStream is2 =  new FileInputStream("/tmp/bar")) {
         /* do stuff with is1 and is2 */
}

作为参数传递给 try 语句的对象应实现 。看看官方文档java.lang.AutoCloseable

对于旧版本的Java,请查看此答案此答案