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

前端 未结 5 1722
刺人心
刺人心 2020-12-22 12:35

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 me

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 13:01

    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
    }
    

提交回复
热议问题