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?
- 2That makes no sense. Inside the static function, there is no such thing as "the current state", since there's no instance.Kerrek SB– Kerrek SB2011-09-22 23:44:36 +00:00Commented Sep 22, 2011 at 23:44
- 1This doesn't make sense. Why would you have to that?NullUserException– NullUserException2011-09-22 23:44:37 +00:00Commented Sep 22, 2011 at 23:44
- 2Provide some code of what you're trying to do, as well as a description of the actual problem (in terms of your functional requirements, not technical constraints).corsiKa– corsiKa2011-09-22 23:54:45 +00:00Commented Sep 22, 2011 at 23:54
- Down-vote will be changed to an up-vote once the original poster clarifies their original post as has been repeatedly requested. At present it's unanswerable.Hovercraft Full Of Eels– Hovercraft Full Of Eels2011-09-23 00:21:02 +00:00Commented Sep 23, 2011 at 0:21
5 Answers
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 } Comments
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.
Comments
A non static member variable "is state". It's the state of a specific instance of that class.
When you say you want to access a non-static member variable, it's as good as saying "want to access a non-static member variable of a specific instance of class XXX", I mean the bolded part is implicit.
So it doesn't make sense to say "I can access it with new instance".