1

我有一个最终变量 ,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
    }
}
4

3 回答 3

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); 
}
于 2013-10-25T17:17:47.877 回答
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;
     }
 }
于 2013-10-25T17:19:35.517 回答
1

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

private final CannonSet save;

public CannonManager(ManCannon plugin) {
    CannonSet temp = null;
    /* code .... */
    if (temp == null) {
        this.save = new CannonSet();
    } else {
        this.save = temp;
    }
}
于 2013-10-25T17:20:28.747 回答