简体   繁体   English

该最终变量将如何被分配且未初始化?

[英]How would this final variable be already assigned and not initialized?

I have a final variable, save , that is a serializble class for some information. 我有一个最终变量save ,它是一些信息的可序列化类。 What I've attempted to do is to set a final variable as that serializable class, however I get some conflicting warnings. 我试图做的是将最终变量设置为该可序列化的类,但是我收到一些冲突的警告。 I'm attempting to make it so that if the file isn't loadable / doesn't exist, it will simply create a new instance, otherwise it will use the old one. 我正在尝试使其无法加载/不存在,它将仅创建一个新实例,否则将使用旧实例。

My issue as it stands is commented in the code at the constructor opening, closing, and on reading the object from the ObjectInputStream 我目前的问题在构造函数的打开,关闭以及从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
    }
}

You can't do this to a final variable: 您不能对最终变量执行此操作:

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

If save was initialized - and only in this case comparison to null is possible, then you can't reassign it. 如果save已初始化-仅在这种情况下可以与null比较,那么您将无法重新分配它。

Conditional logic is possible with final variables and in many cases it looks similar to: 最终变量可以使用条件逻辑,在许多情况下,条件逻辑类似于:

final CannonSet save;

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

It looks like you just need to declare your temp object at full method scope, test if it's null at the bottom where you are checking this.save instead, and then do the assignment. 看起来您只需要在完整的方法范围内声明temp对象,然后在检查this.save的底部测试它是否为null,然后进行赋值即可。 Basically, just have one line ONLY where you assign the instance field. 基本上,只有一行可以分配实例字段。 Abbreviated from your code: 从您的代码缩写:

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;
     }
 }

I found that using a temp variable throughout the constructor made this a lot simpler: 我发现在整个构造函数中使用temp变量会使此过程变得更加简单:

private final CannonSet save;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM