How does an enum singleton function?

爱⌒轻易说出口 提交于 2019-11-30 23:29:55

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

If you disassemble the enum/class after you compile with-

javap Example

You get-

Compiled from "Example.java"
public final class Example extends java.lang.Enum<Example> {
    public static final Example INSTANCE;
    public static Example[] values();
    public static Example valueOf(java.lang.String);
    public static Example getInstance();
    static {};
}

As you can see INSTANCE is a public static final field of Example class.

If you disassemble your EmployeeClass, you get-

public class ExampleClass {
    public static ExampleClass instance;
    public ExampleClass();
    public static ExampleClass getInstance();
}

Do you see now the differences? It's essentially the same with minor differences.

I suggest to read Item 3: Enforce the singleton property with a private constructor or an enum type from Effective Java by Joshua Bloch which explains how it works and why to use enum as a Singleton.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!