Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize from a file to different class

I serialize a ArrayList<packageA.Changelog> list to a file and transmitted the file to another system in another machine.

And since it's a different system that received the file, I don't have the same packageA.Changelog class, instead is a packageB.Changelog which has exactly same structure but in different package.

And when I use

ArrayList<packageB.Changelog> changelogs = (ArrayList<packageB.Changelog>)ois.readObject();

to read out from the file I got a ClassCastException.

How to avoid this exception? Do I need to create the same package structure in the other system only for receiving the list?

like image 344
Aloong Avatar asked Aug 09 '11 09:08

Aloong


People also ask

How do you serialize and deserialize a class?

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class. We must have to implement the Serializable interface for serializing the object.

Which method is used to deserialize an object?

The ObjectInputStream class contains readObject() method for deserializing an object.

How do you deserialize data?

Deserialization is the process of reconstructing a data structure or object from a series of bytes or a string in order to instantiate the object for consumption. This is the reverse process of serialization, i.e., converting a data structure or object into a series of bytes for storage or transmission across devices.


1 Answers

Yes, there are one of the three things you can do.

  1. Create the same class with the same package name

  2. Create an interface(ofcourse again in the same package on both the machines) and ship it on client machines. All your classes can implement this interface even in different packages. For example, your interface can be named Loggable and it should have all the methods declared which are in ChangeLog class right now.

  3. Or finally instead of using the class "ChangeLog" just completely avoid using it and use a HashMap instead which is serializable by default. And you will not have to ship anything to your client(other) machine. You will be able to serialize ArrayList and convert it back to object on other machine.

All the Classes which implement class Loggable can then cast to that type. I hope this helps

like image 119
Sap Avatar answered Oct 04 '22 06:10

Sap