Java - Modifying serialVersionUID of binary serialized object

大憨熊 提交于 2019-11-30 20:27:50

问题


A few months back I serialized a java.io.Serializable object into a file. Now I need to read the contents, but since then the serialVersionUID has changed, and now I'm getting a "class incompatible" error. I know for a fact that none of the data members have changed, so the only barrier is the serialVersionUID check.

Is there a way to either disable the check or to modify the serialVersionUID in the binary file?

CLARIFICATION

This question is assuming that I can't edit the source. Is there a way I can hack the .class file or perhaps hack the serialized object file (use a hex editor and change a value at some certain offset)?


回答1:


As a hack, you can generate the serialVer your jvm is probably using using the serialver tool:

serialver -classpath whatever com.foo.bar.MyClass

If you then manually set the serialVerUID in your class it ought to match and you ought to be able to load, assuming you haven't changed the class in such a way as to invalidate.




回答2:


Why not modify the serialVersionUID in your current version instead as described in the Serialization documentation?




回答3:


I recently found myself in a similar situation--I had some serialized objects that I had to read, the serialVersionUID of those objects was different than the newest version and, in my case, there were a couple of different serialVersionUIDs stored in the file for the same class (stored at different times, obviously). So I didn't have the luxury of modifying the class and setting its serialVersionUID; I actually had to go in and modify the stored data.

What I figured out (by reading the java.io source code) is that an object gets serialized by first storing the class name (using writeUTF()) and then immediately after using writeLong() to save the serialVersionUID.

My solution was to catch the exception then go back, look for the class name, and immediately after the class name replace the old serialVersionUID with the new.




回答4:


It is documented that Serialization is not intended to be used for persisting data. In order to get that data back, you will need to downgrade your version of the JVM to the version that was used to output that data.

For future reference, don't use serialization to persist data between sessions of the JVM.



来源:https://stackoverflow.com/questions/444909/java-modifying-serialversionuid-of-binary-serialized-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!