Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java impose final programmatically

Tags:

java

final

What's the proper way to ensure a value only gets set once, although the time it will be set is unknown (ie: not in the constructor). I could do a null check or keep track of a flag and throw an exception - but what exception should I throw? It's for a small, localized library and I prefer not to create my own ValueAlreadyAssigned exception for such a seemingly generic case.

like image 816
Raekye Avatar asked Dec 12 '22 15:12

Raekye


1 Answers

In the setter. Do it like this:

private foo bar;

public void setFoo(foo bar) {
    if (this.bar == null) {
        this.bar = bar;
    } else {
        System.out.println("Don't touch me!");
        // J/K Throw an IllegalStateException as Michal Borek said in his answer.
    }
}
like image 194
Geeky Guy Avatar answered Dec 30 '22 10:12

Geeky Guy