Java中的枚举类初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19971982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:57:51  来源:igfitidea点击:

Enum class initialization in Java

javaenumsinitialization

提问by Ruchira Gayan Ranaweera

In Java we can do the following to initialize class and call method inside that class:

在 Java 中,我们可以执行以下操作来初始化类并调用该类中的方法:

public class MyClass {
  public String myClassMethod() {
    return "MyClass";
  }
}

.

.

public class Test {
  public static void main(String[] args) {
    MyClass myClass = new MyClass(); // initialize MyClass
    myClass.myClassMethod();// call a method      
  }
}

If my class is an enumclass, implementation will be the following:

如果我的类是一个enum类,则实现如下:

public enum MyEnumClass {
  INSTANCE;
  public String myEnumClassMethod() {
    return "MyEnumClass";
  }
}

.

.

public class Test {
  public static void main(String[] args) {
    MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
    myEnumClass.myEnumClassMethod();
  }
}

Both of these cases works in the same way, but it is said to be better in the enumimplementation. My question is why and how it is happening?

这两种情况的工作方式相同,但据说在enum实现上更好。我的问题是为什么以及如何发生?

回答by vikingsteve

It's a simple implementation of the Singleton pattern, relying on the mechanisms of how Enum's work.

它是单例模式的简单实现,依赖于 Enum 的工作机制。

If you use MyEnumClass.INSTANCEa second time, you'll get the same object instance.

如果您MyEnumClass.INSTANCE再次使用,您将获得相同的对象实例。

In contrast, new MyClass();will create a new object.

相反,new MyClass();会创建一个新对象。

See also discussion here:

另请参阅此处的讨论:

What is the best approach for using an Enum as a singleton in Java?

在 Java 中使用 Enum 作为单例的最佳方法是什么?

There would possibly be more to learn by reading Java Language Spec Section 8-9

通过阅读Java 语言规范第 8-9 节,可能会有更多内容需要学习

回答by Boris the Spider

An enumis essentially a singleton pattern.

Anenum本质上是一种单例模式。

The JVM handles the initialization and storage of enuminstances. To see this most clearly you can write:

JVM 处理enum实例的初始化和存储。要最清楚地看到这一点,您可以编写:

public enum MyEnumClass {
    INSTANCE("some value for the string.");

    private final String someString;

    private MyEnumClass(final String someString) {
        this.someString = someString;
    }

    public String getSomeString(){
        return someString;
    }
}

And in another class:

在另一堂课中:

public static void main(String[] args) {
    final MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
    system.out.println(myEnumClass.getSomeString());
}

This would print out "some value for the string.".

这将打印出“字符串的某个值。”。

This demonstrates that the enuminstances are initialised at class load time, i.e. as if by the staticinitialiser.

这表明enum实例在类加载时初始化,即好像由static初始化程序初始化。

Or put another way, if you do not overwrite equalsin MyClassthen

或者换一种说法,如果你不覆盖equalsMyClass随后

new MyClass() == new MyClass();

Is always false, whereas:

永远false的,而:

MyEnumClass.INSTANCE == MyEnumClass.INSTANCE;

Is always true. i.e. MyEnumClass.INSTANCEis always the sameMyEnumClass.INSTANCEwhereas a new MyClassis created every time your call new MyClass().

始终true。即MyEnumClass.INSTANCE始终不变的MyEnumClass.INSTANCE,而MyClass创建的每个时间您的来电new MyClass()

This brings us nicely to your question of "better".

这让我们很好地解决了您的“更好”问题。

An enumis a singleton instance with various nifty methods for converting Stringenumnames into a reference to the singleton instance that it represents. It also guarantees that if you de-serialize an enumthere won't be two separate instances like there would for a normal class.

Anenum是一个具有各种漂亮方法的单例实例,用于将Stringenum名称转换为对它所代表的单例实例的引用。它还保证,如果您反序列化一个enum,则不会像普通类那样有两个单独的实例。

So an enumis certainly much better as a robust and threadsafe singleton than a class.

因此,enum作为一个健壮且线程安全的单例,an肯定比 a 好得多class

But we cannot have two instances of INSTANCEwith the different values for someStringso the enumis useless asa class...

但是,我们不能有两个实例INSTANCE有不同的值,someString所以enum是无用class...

In short enums are good for what they're good for and classes are good for what they're good for. They are not substitutes and therefore cannot be compared in any meaningful way expect when one is used as the other.

简而言之,enums 对他们的好处有好处,classes 对他们的好处有好处。它们不是替代品,因此不能以任何有意义的方式进行比较,除非将一个用作另一个。