Cases and possibilities of using Java enums mutes?

综合编程 2018-01-01 阅读原文

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;

    public String toString() {
      return str;

  public static void main(String[] args) {
    EnumTest.TATA.str = "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.

One possible usecase would be lazy initialization (calculate some field values when they are first used, if often they are not used at all), or a "normal" mutable singleton object (like a registry or such).

In most cases, though, enum objects should be immutable, and their fields be final.

Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!


Improving Testability of Java Microservices with C... Key Takeaways In enterprise test scenarios, software needs to be tested in the same way as it will run in production, in order to ensure th...
Generate a Java class from a Java application I am trying to create a data validation program that checks if a specific data type is valid by running each "type" (eg. name, age, gender) through it...
JAVA 画图板实现(基本画图功能+界面UI)二、功能实现及重绘实现... 上篇博客中介绍了界面的实现方法,在这篇博客中将对每个按钮的功能的实现进行讲解并介绍重绘 首先肯定要添加事件监听机制了,那么问题来了,事件源对象是谁?需要添加什么方法?事件接口是什么? 1、我们需要点击按钮,获取按钮上的文字信息,颜色信息,粗细信息。那么,此时事件源对象就是按钮,监听方法就是a...
Java – Are if-thread statements secure&q... This might be a stupid question but.. let's assume I have a class ContainerClass, if contains a HashSet that is accessed from several threads that ad...
Java – JList Clicking I have a JList with a JScrollPane . If I only have one thing in the JList , there will be empty space due to the JScrollPane . If I click...