Search code examples
javaserializationdeserializationclassname

Does changing the class name affect Java Deserialization?


I am making a modification and a separate application that allows replays to be saved for a certain game.

What I have to serialize and deserialize is an 2 arrays of class ContO, arrays of class Plane, Trackers, and a class Medium, and that is no problem.

To extend this functionality, I decide to reconstruct it in the separate application so that it supports 2 versions of said game. The way I plan to do this is to use abstract classes named Medium, ContO, Plane, and Trackers, and the classes that will extend those will be named things like MediumVersion1 and MediumVersion2, ContOVersion1, and so on.

In the original game files the class is named ContO, Plane, Trackers, and Medium for both versions, and what I wonder is: by changing the name of the class to reflect the version of the file that will be deserialized, will it effect the deserialization process?

For example, I serialize the class as the name of ContO in the original game files, but deserialize it under a new class name named ContOVersion1, but contains the exact same variables.


Solution

  • I just tried this and the answer is you cannot change the class name. You will end up with a ClassCastException when you try to cast the object you get back from ObjectInputStream.readObject() into your new class with a different name. This is the case even if you keep the same serialVersionUID on both classes.