对于Eclipse,为什么要使用try-with arm来管理它呢?
BufferedReader reader = null;
try {
if (condition) {
try {
reader = method1();
} catch (Exception e) {
...
}
}
if (reader == null) {
reader = method2();
}
do things ...
} catch(Exception e) {
...
} finally {
if (reader != null) {
reader.close();
}
}有没有更好的方法来处理这种情况?或者只是来自eclipse的垃圾警告?
此案例无效:
try (BufferedReader reader = null) {
if (condition) {
reader = method1();
} else {
reader = method2();
}
do things ...
}发布于 2014-01-22 19:44:45
尝试:
try (BufferedReader reader = createBufferedReader(condition)) {
do things ...
}
private BufferedReader createBufferedReader(boolean condition){
if (condition) {
return method1();
} else {
return method2();
}
}发布于 2014-01-22 20:03:04
正如jls-14.20.3中的Java声明的那样
在ResourceSpecification中声明的资源如果没有显式声明,则被隐式声明为最终 (§4.12.4)。
因此,您不能在try块中更改它。如果您希望能够对其进行更改,请使用标准try-catch-finally块。另一种选择是在将其与try- with -resources一起使用之前确定正确的资源。
发布于 2015-11-21 23:32:47
您不一定需要像Seby的答案中那样的可调用或lambda表达式。
考虑到这个问题非常简单,您可以简单地使用一个三元运算符,它适用于所有版本的java。
final String s = "abc";
try (BufferedReader reader = (condition) ? method1() : method2();) {
do things ...
} catch (Exception e) {
...
}https://stackoverflow.com/questions/21281867
复制相似问题