0

I've got a Java object which uses a singleton (e.g. somewhere in the object's code is Singleton.getInstance()). I'm switching over to using dependency injection (Dagger 2), and the standard way to do it would be to create a factory for this class, have the DI framework inject the singleton into the factory, and have the factory pass the singleton to the object's constructor (along with the other arguments), which would store it in a member variable.

But this object is serializable. Marking the member variable containing the singleton transient allows serialization to happen, but when the object is deserialized the member variable is null. What's the best way to get the dependency again after deserialization?

Erik Browne
  • 965
  • 10
  • 19
  • Possible duplicate of [How to serialize static data members of a Java class?](http://stackoverflow.com/questions/1008023/how-to-serialize-static-data-members-of-a-java-class) – Paul Dec 09 '16 at 19:17

1 Answers1

0

Well it may seem a bit simple, but the answer really is that you need to re-assign that field after deserialization. In particular, setting that field is usually either done with a setter or an init method in the object, depending on the effect of the field to the object. If possible, it might be easy to assign it right after the object is deserialized.

Rabbit
  • 131
  • 2