squirrelsareduck
squirrelsareduck

Reputation: 884

Java serialization: static variables not serializable: workaround

Ok, so this question is mostly just related to: is there a better way to do this?

I have a phonebook application, and you can add users to it, delete them, and such, with each person being assigned a distinct ID#. A Person class stores lastIDused as a static class variable. The phonebook class has a vector of Persons.

My workaround thought is this: create a new non-static variable for the Person class, and upon serializing/saving, for the 1st element in the vector only, store the static variable's data into this new variable. Then, when de-serializing, re-set the static variable using the 1st Person's such-variable.

Going back to my original question: is there a better/more-formal/proper way to do this?

Upvotes: 0

Views: 777

Answers (2)

Stephen C
Stephen C

Reputation: 718708

A better solution (IMO) would be to make lastIdUsed an instance field of the PhoneBook class. It sounds like you are already serializing an instance of that class ...

FWIW - making lastIdUsed an instance field of Person is just bad object modelling. The field is almost never going to be useful and almost never going to have a valid value. It will only have a valid value in the case of the first serialized Person in a PhoneBook.

Upvotes: 3

Todd
Todd

Reputation: 31660

First, I would avoid this kind of thing entirely. Static variables aren't serializable for a reason, namely by deserializing something you would invalidate the state of other objects. For example, if your lastUsedId is at 10 and you deserialize an object where it was at 5, it could lead to creating duplicates (6-10).

However, if you are still going to do this, check out the Externalizable interface. It lets you control the serialization and deserialization of an object. Here[1] is a good discussion on it. In the past I've used Externalizable to more tightly control the format of the object being serialized in order to save space. If you really want to, you could serialize a static variable and set it when you deserialize. You could even only set it if it is higher than the value currently in memory. Again, like other commenters I would advise against this approach entirely, but it doesn't hurt to learn this stuff, eh?

[1] What is the difference between Serializable and Externalizable in Java?

Upvotes: 0

Related Questions