How to deserialize from a file to another class

I serialize the ArrayList<packageA.Changelog> list to a file and transfer the file to another system on another computer.

And since this is another system that received the file, I do not have the same packageA.Changelog class, but there is packageB.Changelog , which has exactly the same structure, but in a different package.

And when I use

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

to read from a file, I got a ClassCastException .

How to avoid this exception? Do I need to create the same package structure on another system just to get a list?

+6
source share
2 answers

Yes, there is one of three things you can do.

  • Create the same class with the same package name

  • Create an interface (of course, in the same package on both machines) and send it to the client machines. All your classes can implement this interface even in different packages. For example, your interface can be called Loggable, and it should have all the declared methods that are in the ChangeLog class right now.

  • Or finally, instead of using the "ChangeLog" class, just completely avoid using it and instead use the HashMap, which by default is serialized. And you do not have to send anything to your client (other) machine. You can serialize an ArrayList and convert it back to an object on another machine.

All classes that implement the Loggable class can then be passed to this type. Hope this helps

+5
source

I do not have the same packageA.Changelog class, but there is packageB.Changelog , which has exactly the same structure, but in a different package.

Why? This is problem. Do not do this.

-1
source

Source: https://habr.com/ru/post/894617/


All Articles