综合编程

Cases and possibilities of using Java enums mutes?

微信扫一扫,分享到朋友圈

Cases and possibilities of using Java enums mutes?
0

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.

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!

Kscope Submission Ideas

上一篇

How can I use the Parse push plug-in in an Ionic 2 application?

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Cases and possibilities of using Java enums mutes?

长按储存图像,分享给朋友