问题描述
编辑:回答 - 错误是方法不是静态
我使用 singleton设计模式
public class Singleton { private static final Singleton INSTANCE = new Singleton(); // Private constructor prevents instantiation from other classes private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
我尝试过:
Singleton singleton = new Singleton(); // error - constructor is private Singleton singleton = Singleton.getInstance(); // error - non-static method cannot be referenced from a static context
什么是正确的代码?
谢谢, Spencer
推荐答案
Singleton singleton = Singleton.getInstance();
是正确的方法.确保您的getInstance()方法确实是static.
由于您的Singleton实现远非安全 - 您的对象可以通过反射实例化,因此您可能需要基于
I'm used the Singleton Design Pattern My question is how do I create an object of class Singleton in another class? I've tried: What is the correct code? Thanks,
Spencer is the correct way. Make sure your getInstance() method is indeed static. Since your Singleton implementation is far from being safe - your object can be instantiated via reflection, you may want to create a singleton based on enum Singleton singleton = Singleton.getInstance(); should work -- that error doesn't make sense, given your code; are you sure you're reporting it correctly? (It would make sense if you had forgotten to make the getInstance method static, which you've done in your code above.) The code you've given us for the class is correct. Lastly, one conceptual note: First, you aren't "creating an object of class Singleton" -- that's the whole point of a Singleton. :) You're just getting a reference to the existing object. This one: should work. This is how you call static methods in Java. And the getInstance() method is declared as static. Are you sure you are using the very same Singleton class? Or maybe you have imported a class called the same in some other package. public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
Singleton singleton = new Singleton();
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context
推荐答案
Singleton singleton = Singleton.getInstance();
其他推荐答案
其他推荐答案
Singleton singleton = Singleton.getInstance();