gpt4 book ai didi

java - 在尝试使用之前创建的资源语句中使用资源

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:47 26 4
gpt4 key购买 nike

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

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

现在我的问题是,为什么我必须在 try 语句中创建对象?为什么我不允许在这样的语句之前创建对象:

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 block 中,这允许编译器使用它们来生成清理所需的 close 样板文件。

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 9 开始,要求放宽了;如果原始变量实际上是最终的,则不必在 try block 中重新声明变量。

JEP 213

关于java - 在尝试使用之前创建的资源语句中使用资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com