简体   繁体   中英

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. 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

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.

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. 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:

private final CannonSet save;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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