how to access a non static member from a static method in java?

I have a situation where i have to access a non static member from inside a static method. I can access it with new instance, but current state will be lost as non static member will be re-initialized. How to achieve this without losing data?


Maybe you want a singleton. Then you could get the (only) instance of the class from within a static method and access its members.

The basic idea is

public class Singleton {
  private static Singleton instance = null;

  private Singleton() {}

  public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
  }
}

and then in some static method:

public static someMethod() {
    Singleton s = Singleton.getInstance();
    //do something with s
}

What you are asking for doesn't really make sense. Just make your method non-static because your static method cannot be tied to an instance.


Static methods do not apply to a particular instance/object, they're a class-level thing. Because of that, they're not given an instance reference. So, no you cannot do this.

If you can work out which instance reference to use another way, you could access the non-static methods of it.

Or, alternatively, re-architect your classes so that it's a non-static method.

链接地址: http://www.djcxy.com/p/96366.html

上一篇: 在pthreads中使用成员函数(Linux)

下一篇: 如何从Java中的静态方法访问非静态成员?