Debanjan
Debanjan

Reputation: 2836

Deserialize objects, whose class serialVersionUID has changed in Java

There is a class User that implements Serializable, but didn't have a serialVersionUID defined in first version. In the next version I have provided a final serialVersionUID.

Now the problem is whenever I try to deserialize the User objects that were stored earlier, I get the error:

static final long serialVersionUID =4061053075992556495L; but expected com.example.android.User: static final long serialVersionUID =-1079331593441085712L;

I am using FileInputStream to read the data.

FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
User object = (User) ois.readObject();
ois.close();

Is there any way to deserialize the old objects to this serialVersionUID?

Upvotes: 3

Views: 1421

Answers (1)

GhostCat
GhostCat

Reputation: 140427

That is the thing with java serialization: when you messed up like this, you are often broken for good.

But maybe it is as simple as EJP suggests (and is right most often). Then you simply change your current class to have that serial uid that the message tells you to use.

If the chances you made to your class version after creating those those files are compatible, then you might be able to solve your problem that way.

If that doesn't work out: turn back your class definition to the old setup. Deserialize those files - and serialize them into another more robust format, for example JSON. Then you can go forward and re-use the JSON content with newer versions of your class that come with changes to the class structure.

Or accept that you lost those files. That is one of the consequences of using concepts without fully understanding them. Painful but sometimes almost inevitable.

Finally: there is one other option. The Java serialization format follows a standard procedure. So it is possible to write a parser for this binary representation of your objects (it would not surprise me if you can find existing tooling doing that for you).

Meaning: if the content of those files is really important to you, you might be able to access the information within the files. You aren't able to deserialize them the "normal" way, but the information is still there and might be accessible, given some effort.

Upvotes: 4

Related Questions