cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Walker 123 更新时间:2023-11-29 05:16:35 28 4
mua khóa gpt4 Nike

我注意到这不会编译:

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

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

}

与:Error:(17, 24) java: expected

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

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

}

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

câu trả lời hay nhất

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

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
Đề xuất bài viết: ios - Swift:异步回调
Đề xuất bài viết: mysql - 提取不同的成员名称及其计数
Đề xuất bài viết: ios - 使用 RxSwift 时未设置 Tableview 数据
Đề xuất bài viết: php - mysql left join好像不行
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress