0

I have a Pilot class, and an instance of that class: bobThePilot.

I serialize bobThePilot to a String and copy that to my my hard disk. Then I create a new project and recreate the Pilot class (exactly identical as before)....

And then I create newBobThePilot in this new project by de-serializing the String which I got from my disk. But it fails. Everybody said it was because of something named serialVersionUID.

Is it possible to do that (serialize and deserialize in different classes (although exactly identical class)? If so, how?

Thanks.

Morals:

  1. add serialVersionUID attribute to our serialized class Example:
    private static final long serialVersionUID = 1L;
  2. implements serializable to all classes which related to our serialized class
smftr
  • 923
  • 3
  • 17
  • 31
  • 1
    Why would you recreate a class instead of reusing the one you already have? Anyway, the class is probably not *exactly* the same. Post the source code of both classes, from the package statement to the last line. Also, post the stack trace of the exception you got, and the code used to serialize/deserialize. Serializing to a String is dubious: serialization produces bytes. – JB Nizet Jul 01 '14 at 21:36
  • 1
    What do you mean by "it fails"? What exactly are you seeing? – Ryan J Jul 01 '14 at 21:39
  • Show us the error (stack trace) – Steve Kuo Jul 01 '14 at 23:29
  • Your second 'moral' isn't correct. You can extend your classes as much as you like. The mistake was to serialize one class and expect to be able to deserialize as another class. – user207421 Jul 02 '14 at 01:46

2 Answers2

0

If you don't put a serial version id, the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class. Even though the classes are identical, different versions of the JDK can create different serialversionuids.

Andres
  • 10,561
  • 4
  • 45
  • 63
  • 1
    The Java compiler does not 'create one for you'. A default value is computed *at runtime* if the field isn't present. Your final sentence is therefore incorrect as well. – user207421 Jul 01 '14 at 21:37
  • so when i add the attribute "**private static final long serialVersionUID = 1L;**" in both (new and old project) Pilot class it would be able? but that still unable – smftr Jul 01 '14 at 22:32
  • oh great, my fault is i **extends** my **Pilot** class. – smftr Jul 02 '14 at 00:46
0

But it fails.

Fails how?

Everybody said it was because of something named serialVersionUID.

Not unless the error message said so. Mor likely it was because of your original error of using String as a container for binary data. It isn't. Just write the actual bytes, don't round-trip them via String.

Is it possible to do that (serialize and deserialize in different classes

No.

user207421
  • 305,947
  • 44
  • 307
  • 483