Java单例内部类
我知道Java中单例的概念。 我在 Java 中创建单例作为内部类时遇到问题。问题发生在持有者的
public class NormalClass {
private class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private static class SingletonHolder {
private static Singleton sessionData = new Singleton();
}
public static Singleton getInstance() {
return NormalClass.Singleton.SingletonHolder.sessionData;
}
}
public void method1() {
Singleton.getInstance();
}
}
错误是在 new Singleton() 构造函数调用时。如何正确调用 Singleton 的私有构造函数作为内部类?
问候
I know the concept of singleton in Java.
I'm having problems with creating singleton as inner class in Java. Problem occurs at holder's
public class NormalClass {
private class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private static class SingletonHolder {
private static Singleton sessionData = new Singleton();
}
public static Singleton getInstance() {
return NormalClass.Singleton.SingletonHolder.sessionData;
}
}
public void method1() {
Singleton.getInstance();
}
}
Error is at new Singleton() constructor call. How to proper call private constructor of Singleton as inner class?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果它应该是真正的单例,请将您的单例类设为静态。然后你就可以调用构造函数了。
Java 嵌套类< 中解释了构造函数调用不起作用的原因/a> 教程。基本上,内部类需要外部类的实例才能构造:
If it should be a real singleton, make your singleton class static. Then you will be able to call the constructor.
The reason why your constructor call does not work is explained in the Java nested classes tutorial. Basically, the inner class requires an instance of the outer class before it can be constructed:
不能在非静态类中声明静态类。将
Singleton
类设为静态,一切都应该可以正常编译。You cannot declare static classes within a non-static class. Make the
Singleton
class static and everything should compile just fine.问题是内部类不是静态内部类,
The problem is that the inner class is not static inner class,
按需初始化... Joshua Bloch ..
我认为如果你的内部类是静态的,那么你的持有者类也应该是静态的。
或者为什么不喜欢这样呢?为什么要有内部持有者类别?
Initialize on Demand.... Joshua Bloch..
I think if your inner class is static, your holder class should also be static.
Or Why not like this? why an inner holder class at all ?