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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can't. A static method is not associated with any particular state (aka any non-static members). In other words, they operate independently of any particular instance of the class so they cannot depend on non-static members.
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".
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.
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
and then in some static method:
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.