尝试使用资源为什么不能修改资源

E2r*_*abi 3 java try-catch variable-assignment java-8 try-with-resources

我尝试将参考扫描的值设置为null时发现无法编译的try资源示例

try(Scanner scan = new Scanner(System.in)) {
    String s = scan.nextLine();
    System.out.println(s);
    scan = null;
}
Run Code Online (Sandbox Code Playgroud)

我问这个编译错误背后的规则是什么,我在网上做了一些搜索,但是没有找到解释它的规则。谢谢您的解释:=)

And*_*lko 8

这是设计使然。您不能重新分配final变量。

14.20.3。尝试资源

如果未明确声明资源规范中声明final的变量,则将隐式声明该变量final(第4.12.4节)。

  • 值得一提的是try-with-resources不需要*声明*变量。即使它们不是最终变量,它也可以接受已经存在的变量,例如`PrintWriter pw = new PrintWriter(“ path / to / file”); try(pw){pw.write(“ foo”); }`。但这还要求不要重新分配这些变量(即使在try-with-resource块之外)-它们必须有效地是final。 (4认同)