如何从文件反序列化到不同的类 [英] How to deserialize from a file to different class

查看:254
本文介绍了如何从文件反序列化到不同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我序列化 ArrayList< packageA.Changelog>列表到一个文件并将文件传输到另一台机器的另一个系统。

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

由于它是收到文件的另一个系统,我不知道没有相同的 packageA.Changelog 类,而是一个 packageB.Changelog ,它具有完全相同的结构但不同包。

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.

当我使用

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

从文件中读出我得到了 ClassCastException

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?

推荐答案

是的,您可以做以下三件事之一。

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


  1. 使用相同的包名创建相同的类

  1. Create the same class with the same package name

创建一个接口(当然在同一个包中)在两台机器上)并将其运送到客户端机器上。即使在不同的包中,您的所有类都可以实现此接口。例如,您的接口可以命名为Loggable,它应该具有在ChangeLog类中声明的所有方法。

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.

或者最后不是使用类ChangeLog完全避免使用它并使用HashMap代替默认情况下可序列化的HashMap。而且您不必向您的客户(其他)机器运送任何东西。您将能够序列化ArrayList并将其转换回其他机器上的对象。

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.

所有实现类的类然后,Loggable可以转换为该类型。
我希望这有助于

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

这篇关于如何从文件反序列化到不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆