0

I have old binary data serialized and stored in a db with an old class 'mypackage.Myclass'

I would like to refactor this class to 'mypackage.topic.Myclass' and still able to read the binary data back (deserialization)

I get an error Classnotfound when :

                    ois = new ObjectInputStream(bos);
                    o = ois.readObject();
mypackage.topic.Myclass myclass = (mypackage.topic.Myclass) o;

Is there a way to force readObject() to match another class then the original serialized class ? Or any otherhint doing this ?

mcfly soft
  • 11,289
  • 26
  • 98
  • 202
  • see ["readobject method throws ClassNotFoundException"](https://stackoverflow.com/questions/2916107/readobject-method-throws-classnotfoundexception). – elirandav Mar 29 '19 at 07:50

1 Answers1

1

You can solve this by creating a data wrapper class called mypackage.Myclass. When deserializing the binary data, you can first try to deserialize it as mypackage.topic.Myclass. When this fails, deserialize it as mypackage.Myclass and convert it afterwards to the class mypackage.topic.Myclass.

You can also set the serialVersionUID of the mypackage.topic.Myclass to the serialVersionUID of the mypackage.Myclass. If you don't know the serialVersionUID of the class mypackage.Myclass, or if you doesn't have set the serialVersionUID, you can generate the serialVersionUID, which is probably used/automatically created by the JVM using this command: serialver -classpath whatever com.foo.bar.MyClass (See: Java - Modifying serialVersionUID of binary serialized object)

When the classes have the same serialVersionUID, there will be no error when you deserialize the class.

Marvin Klar
  • 1,869
  • 3
  • 14
  • 32
  • Thanks for helping. I wanted to simplify my code and restructuring and avoid creating new classes. So there is no other way to do ? – mcfly soft Mar 29 '19 at 16:30