以前,而不是使用枚举,我会做这样的事情:
public static ExampleClass instance; public ExampleClass(){ instance=this; } public static ExampleClass getInstance(){ return instance; }然后有人告诉我一个枚举单例:
public enum Example{ INSTANCE; public static Example getInstance(){ return Example.INSTANCE; }在第一个例子中,我必须实例化对象才能创建实例。 有了枚举,我不需要那样做......至少看起来是这样。 有人能解释这背后的原因吗?
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
更多推荐
发布评论