gpt4 book ai didi

java - 为什么不能在 try-with-resources try 子句中重用引用变量?

转载 作者:行者123 更新时间:2023-11-29 05:16:35 28 4
gpt4 key购买 nike

我注意到这不会编译:

PrintWriter printWriter = new PrintWriter("test.txt");
printWriter.append('a');
printWriter.close();
printWriter = null;

try(printWriter = new PrintWriter("test.txt")) {

}

与:Error:(17, 24) java: <identifier> expected

此时只有一个新变量起作用:

try(PrintWriter printWriter2 = new PrintWriter("test.txt")) {

}

我的直觉是只需要一个新对象,但显然需要一个新引用。显然这是编译时类型检查的结果,但为什么旧引用不起作用?

最佳答案

答案很简单,因为它会在资源尝试完成后关闭。更具体地说,

JLS 14.20.3. try-with-resources部分说(粗体添加),

A ResourceSpecification declares one or more local variables with initializer expressions to act as resources for the try statement.

A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final.

The type of a variable declared in a ResourceSpecification must be a subtype of AutoCloseable, or a compile-time error occurs.

关于java - 为什么不能在 try-with-resources try 子句中重用引用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331705/

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