I don't know if I'm the only one to know that, but the values of an enum are not implicitly final and can be modified.
enum EnumTest {
TOTO("TOTO 1"),
TATA("TATA 2"),
;
private String str;
private EnumTest(String str) {
this.str = str;
}
@Override
public String toString() {
return str;
}
}
public static void main(String[] args) {
System.out.println(EnumTest.TATA);
EnumTest.TATA.str = "newVal";
System.out.println(EnumTest.TATA);
}
TATA 2
newVal
These values are oftenly initialized at instance creation (TOTO("TOTO 1")
) but, except myself, I've never seen anyone using the final keyword for enum variables that should be immutable. That's not the point of the question, just wondering if I'm the only one aware of this.
What I'd like to know is if there was any usecase to create mutable enums?
And I'd also like to know the limits of what we can do with enums (good practice or not).
I've not tested it, but maybe an enum can be injected with Spring beans?
At least it seems we can annotate each instance (@Deprecated works fine for exemple), and also the methods.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…