Java枚举可变性的用途和可能性? [英] Java enums mutability usecases and possibilities?

查看:118
本文介绍了Java枚举可变性的用途和可能性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我是唯一知道的人,但枚举的价值观并不是隐含的,而是可以被修改。

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

值通常在实例创建时初始化( TOTO(TOTO 1)),但是除了我自己以外,我从未看到有人使用final关键字来枚举变量,不可改变的。这不是问题的一点,只是想知道我是唯一知道这一点的人。

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?

我也想知道我们可以用枚举来做什么的限制(良好做法或不)。
我没有测试过,但也许一个枚举可以注入Spring bean?
至少我们可以注释每个实例(@Deprecated可以正常工作),还有方法。

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.

推荐答案

p>一个可能的用例将是懒惰初始化(当它们被首次使用时计算一些字段值,如果通常不被使用)或者正常可变单例对象(如注册表等)。

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

在大多数情况下,枚举对象应该是不可变的,而它们的字段是final。

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

这篇关于Java枚举可变性的用途和可能性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆