java - Problem with: "Variable used as a try-with-resources resource should be final or effectively final"
问题描述
From my point of view, I use try with resources so I don't have to close resources manually in try block. So in case of making a FileWriter
, I wouldn't have to try, then catch and close it in finally, but just do this:
void m1(){
try(FileWriter fileWriter = new FileWriter ("test.txt")) {
//some operations
}catch (IOException ioException){
//some code
}
}
But what if I have a class that takes a reference of already instantiated FileWriter
? Then I get a problem. I think I have a big "hole" in this use-case. Can someone point what am I missing? I tried doing this:
public class Test {
private FileWriter fileWriter;
public Test (FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
public void m1 () {
try(fileWriter) { //compile error
//Says:Variable used as a try-with-resources resource should be final or effectively final
}catch (IOException ioe){
//some code
}
}
}
My only goal was ("as I am lazy") to automatically close the resource using its reference. Unfortunately, it didn't quite work. How to better understand why I get quoted warning?
解决方案
You can use try with resources for any resources created outside the try block if you declare a new variable for the scope of the try block. Change m1 to:
public void m1 () {
try(var autoclosedhere = fileWriter) {
// or try(FileWriter autoclosedhere = fileWriter) {
// now fileWriter will close at the end
}catch (IOException ioe){
//some code
}
}
This works in Java 9 onwards. A local variable in try clause is required so that there is no ambiguity in case fileWriter was changed inside the block - see JDK-7196163.
推荐阅读
- powershell - 有哪些不同的 PowerShell 文件类型?
- python-3.x - 在 Python 3.6 中运行 scrapyd
- javascript - web3-react 导致我的应用程序挂起而没有错误
- javascript - 移动屏幕高度禁用带有文本编辑器的 div 合同
- html - 您是否有任何理由不想更改元素类而不是样式对象的值?
- java - Java,比较 object.s 列表中的字符串
- python - 如何读取csv文件中的所有数据
- pyspark - Pyspark 随机拆分(测试/训练)在一列中的不同值上,其中来自另一列的所有不同值都包含在每个拆分中
- php - 我是否可以通过使用存储过程而不是查询来避免 SQL 注入?
- python - 我怎样才能找到和写一个列表偶数和奇数?