在 if else 语句中使用可选类类型定义变量



我需要根据是否设置参数(opath(来更改类/流类型,但是当我在if-else语句中声明时,netbeans抱怨找不到变量oos。

我不明白这一点,因为 var oos 总是被设置的,而且它不可能是未定义的??

if(_param.get("opath") != null) {
FileOutputStream oos = new FileOutputStream(_param.get("opath").toString());
} else {
OutputStream oos = csocket.getOutputStream();
}
do something with oos...

将代码更改为以下内容

OutputStream oos;    
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
//do something with oos

它只是关于范围并使对象可用于您想要使用它的代码

局部变量的范围是有限的,它是定义块,在这种情况下,是ifelse块,因此无法从外部访问。

您可以将其移出:

OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
do something with oos...

使用三元运算符时不会遇到此问题,该运算符是">if-then-else 语句的简写":

OutputStream oos = _param.get("opath") != null ?
new FileOutputStream(_param.get("opath").toString()) :
csocket.getOutputStream();

在这种情况下,oos立即声明和初始化。

此外,这允许定义变量oos甚至final使用常规 if-else-语句是不可能的。

最新更新