编程语言
首页 > 编程语言> > java – 在try中使用资源,使用之前创建的资源语句

java – 在try中使用资源,使用之前创建的资源语句

作者:互联网

Java 7开始,我们可以使用try资源:

try (One one = new One(); Two two = new Two()) {
    System.out.println("try");
} catch (Exception ex) { ... }

现在我的问题是,为什么我必须在try-statement中创建对象?为什么我不允许在语句之前创建对象,如下所示:

One one = new One();
try (one; Two two = new Two()) {
    System.out.println("try");
} catch (Exception ex) { ... }

我没有看到任何理由,为什么这应该是一个问题.虽然我收到错误消息“此语言级别不支持资源引用”.我将我的IDE(IntelliJ IDEA)设置为Java 8,因此应该可以工作.是否有充分的理由,不被允许?

解决方法:

您不必在try-with-resources语句中创建对象,只需声明一些实现AutoCloseable的类型的局部变量.这些变量实际上是最终的,并且限定在try块中,这允许编译器使用它们来生成清理所需的紧密样板.

FileInputStream f1 = new FileInputStream("test1.xml");
FileInputStream f2 = new FileInputStream("test2.xml");
// Don't need to create the resources here, just need to declare some vars
try (InputStream in1 = f1; InputStream in2 = f2) {
    // error; in1 is final
    in1 = new FileInputStream("t");
}

Better Resource Management with Java SE 7: Beyond Syntactic Sugar.

标签:java,try-with-resources
来源: https://codeday.me/bug/20190715/1465338.html