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

查看:27
本文介绍了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.

推荐答案

一个可能的用例是延迟初始化(在第一次使用时计算一些字段值,如果它们经常根本不使用),或者正常"可变单例对象(如注册表等).

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.

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

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