Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...