[英]How does an enum singleton function?
以前不是使用枚舉,我會做類似的事情:
public static ExampleClass instance;
public ExampleClass(){
instance=this;
}
public static ExampleClass getInstance(){
return instance;
}
然后有人告訴我一個enum單身人士:
public enum Example{
INSTANCE;
public static Example getInstance(){
return Example.INSTANCE;
}
在第一個例子中,我必須實例化對象才能創建實例。 有了枚舉,我不需要這樣做..至少它出現了。 有人可以解釋這背后的原因嗎?
Java編譯器負責將字節字段創建為字節碼中Java類的靜態實例。 關於字節碼的很棒的博客文章(不是我的博客): http : //boyns.blogspot.com/2008/03/java-15-explained-enum.html
如果你在編譯之后反匯編枚舉/類,
javap示例
你得到-
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 {};
}
如您所見, INSTANCE是Example類的公共靜態final字段。
如果你拆卸你的EmployeeClass,你得到 -
public class ExampleClass {
public static ExampleClass instance;
public ExampleClass();
public static ExampleClass getInstance();
}
你現在看到差異嗎? 它與微小的差異基本相同。
我建議閱讀Item 3: Enforce the singleton property with a private constructor or an enum type from Effective Java
Joshua Bloch解釋了它是如何工作的以及為什么將枚舉用作Singleton。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.