简体   繁体   English

Java可序列化失败

[英]Java Serializable failure

I've have a class called Expression that im trying to serialize using the following load()/save() functions. 我有一个名为Expression的类,我试图使用以下load()/ save()函数进行序列化。 It used to work fine, after making some changes to my code and the Expression class, a call to in.readObject() throws ClassCastException . 在对代码和Expression类进行了一些更改之后,它过去可以正常工作,对in.readObject()的调用将引发ClassCastException The error message is: java.lang.ClassCastException: java.lang.String cannot be cast to java.io.ObjectStreamClass 错误消息是: java.lang.ClassCastException:无法将java.lang.String强制转换为java.io.ObjectStreamClass

To me, it feels very bad to store binary data as a String. 对我来说,将二进制数据存储为String感觉很不好。 Try to use a more stable way to store the binary output of the ObjectOutputStream. 尝试使用更稳定的方法来存储ObjectOutputStream的二进制输出。 If you really want to stick with a string formatted approach, try to use Base64 encoding, which is always safe. 如果您真的想使用字符串格式的方法,请尝试使用Base64编码,这始终是安全的。


What I might see as a problem is that you defined the serialUID yourself to a static constant: 我可能会看到的问题是,您自己将serialUID定义为静态常量:

private static final long serialVersionUID = 3L;

This UID is used to determine if the classes in the class path are compatible with the class of the input object. 此UID用于确定类路径中的类是否与输入对象的类兼容。 So what I suspect is that you modified the class without changing the serialVersionUID. 因此,我怀疑您在不更改serialVersionUID的情况下修改了该类。 That made the ObjectInputStream think that is is compatible, but you are still working with old data. 这使ObjectInputStream认为是兼容的,但是您仍在使用旧数据。 Try to get rid of the old data, and restart with a fresh save() call. 尝试清除旧数据,然后重新调用save()重新启动。


Are you sure that Input is serializable as well? 您确定Input也可以序列化吗? That the UID of that class isn't corrupt? 该类的UID没有损坏?

it seems serializable does not like NULL values in the fields of the class members. 似乎可序列化不喜欢类成员字段中的NULL值。 if i make sure that all class members have actual memory it does not fail. 如果我确保所有类成员都有实际的内存,它不会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM