函数中的Java最终变量

GMs*_*soF 2 java final java-ee

void function_ab(){

if ( a == true){
    final Class_A obj = new Class_A("a"); //This is an example scenario, so I couldn't create a setter to pass in "a" instead of passing it into Contructor.
}else{
    final Class_A obj = new Class_A("B");
}

// the code below will access obj object in Inner class.

}
Run Code Online (Sandbox Code Playgroud)

我需要在声明后访问obj,但由于它们是在'if'块中声明的,因此我将无法访问它.我也做不到这样的事情:

void function_ab(){

final Class_A obj = null;
if ( a == true){
    obj = new Class_A("a"); //final variable cannot be changed.
}else{
     obj = new Class_A("B");
}

// the code below will access obj object in Inner class.

}
Run Code Online (Sandbox Code Playgroud)

上面的代码无效.那么让它工作的唯一方法是将obj变量声明为类变量吗?我尽量避免这样声明,因为它只在那个函数中使用.

请告诉我是否有更好的解决方法.

use*_*tbd 12

而不是使用:

final Class_A obj = null;
Run Code Online (Sandbox Code Playgroud)

你应该可以使用

final Class_A obj;
Run Code Online (Sandbox Code Playgroud)

这将允许您obj在if语句中初始化 - 有关更多信息,请查看维基百科的空白决赛的描述,这是我们可能信赖的生活源.