枚举单例如何运作? [英] How does an enum singleton function?
问题描述
以前不用使用枚举,我会做一些类似的例子:
Previously instead of using enums, I would do something like:
public static ExampleClass instance;
public ExampleClass(){
instance=this;
}
public static ExampleClass getInstance(){
return instance;
}
然后有人告诉我一个枚举单身人士:
Then someone told me about a enum singleton:
public enum Example{
INSTANCE;
public static Example getInstance(){
return Example.INSTANCE;
}
在第一个例子中,我不得不实例化对象以创建实例。有一个枚举,我不需要这样做..至少它出现。有人可以解释这个原因吗?
In the first example I had to instantiate the object in order to create the instance. With an enum, I do not need to do that.. at least it appears. Can someone explain the reason behind this?
推荐答案
Java编译器负责将枚举字段创建为Java类的静态实例字节码。伟大的博客文章(不是我的博客)与字节码在这里: http:// boyns。 blogspot.com/2008/03/java-15-explained-enum.html
The Java compiler takes care of creating enum fields as static instances of a Java class in bytecode. Great blog post on it (not my blog) with bytecode here: http://boyns.blogspot.com/2008/03/java-15-explained-enum.html
这篇关于枚举单例如何运作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!