在 Singleton 的基本实现中,new Singleton1()
调用实际发生在什么时候(用 *
标记?
public final class Singleton1 {
private Singleton1() { }
private static Singleton1 instance = new Singleton1(); // (*) When does this happen?
// Before calling getInstance() from the client?
public static Singleton1 getInstance() {
return instance;
}
}
最佳答案
当 JVM 首次加载类时,会填充静态字段(请参阅 JLS 12.4 )。所以是的,instance
将在调用 getInstance()
之前填充。
关于java - Java中静态字段什么时候初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59831360/