public class Singleton{
private static Singleton instance = new Singleton();
private Singleton(){};
public static Singleton getInstance(){
return instance;
}
}
public class Singleton{
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){};
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
public enum Singleton {
INSTANCE;
public void get() {
System.out.println("");
}
}
通过反编译我们看到,枚举是在 static 块中进行的对象的创建。
public final class com.loadclass.test.Singleton extends java.lang.Enum<com.loadclass.test.Singleton> {
public static final com.loadclass.test.Singleton INSTANCE;
public static com.loadclass.test.Singleton[] values();
Code:
0: getstatic #1 // Field $VALUES:[Lcom/loadclass/test/Singleton;
3: invokevirtual #2 // Method "[Lcom/loadclass/test/Singleton;".clone:()Ljava/lang/Object;
6: checkcast #3 // class "[Lcom/loadclass/test/Singleton;"
9: areturn
public static com.loadclass.test.Singleton valueOf(java.lang.String);
Code:
0: ldc #4 // class com/loadclass/test/Singleton
2: aload_0
3: invokestatic #5 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast #4 // class com/loadclass/test/Singleton
9: areturn