该最终变量如何分配而不是初始化?

时间:2013-10-25 17:09:54

标签: java

我有一个最终变量save,它是一个可序列化的类,用于显示某些信息。我试图做的是将最终变量设置为可序列化的类,但是我得到了一些相互矛盾的警告。我试图这样做,如果文件不可加载/不存在,它只会创建一个新实例,否则它将使用旧实例。

我现在的问题在构造函数的开启,关闭和从ObjectInputStream读取对象的代码中被注释

private final CannonSet save;


public CannonManager(ManCannon plugin) { // Warning that save is not initialized
    if (/* some conditional statement */) {
        //lot of code removed, unnecessary to problem
        //essentially, save was set conditionally here (loaded from file)
        this.save = new CannonSet();
    }
    if (this.save == null) {
        this.save = new CannonSet(); // Warning that save may have already been set
    }
}

3 个答案:

答案 0 :(得分:2)

您无法对最终变量执行此操作:

if (this.save == null) {
    this.save = new CannonSet(); // Warning that save may have already been set
}

如果save已初始化 - 并且只有在这种情况下才能与null进行比较,则无法重新分配。

条件逻辑可以使用最终变量,在许多情况下它看起来类似于:

final CannonSet save;

if(condition1){
    save = new CannotSet(1);
} else
if(condition2){
    save = new CannotSet(2);
} else {
    save = new CannotSet(3); 
}

答案 1 :(得分:2)

看起来您只需要在完整方法范围内声明您的临时对象,测试它是否在您检查this.save的底部为空,然后执行赋值。基本上,只有一行只分配实例字段。从您的代码中缩写:

public CannonManager(ManCannon plugin) {
    CannonSet temp = null;
    try{
       // stuff happens
       temp = (CannonSet) in.readObject();
    }catch( ... ){
       // exception handling
    }
    if(temp == null){
       this.save = new CannonSet();
    }else{
       this.save = temp;
     }
 }

答案 2 :(得分:1)

我发现在整个构造函数中使用临时变量使得这更简单:

private final CannonSet save;

public CannonManager(ManCannon plugin) {
    CannonSet temp = null;
    /* code .... */
    if (temp == null) {
        this.save = new CannonSet();
    } else {
        this.save = temp;
    }
}