Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Serialization 1.4 vs 1.6

I have one java program that has to be compiled as 1.4, and another program that could be anything (so, 1.4 or 1.6), and the two need to pass serialized objects back and forth. If I define a serializable class in a place where both programs can see it, will java's serialization still work, or do I need 1.6-1.6 or 1.4-1.4 only?

like image 800
Nate Parsons Avatar asked Dec 31 '22 07:12

Nate Parsons


2 Answers

Make sure the classes to be serialized define and assign a value to static final long serialVersionUID and you should be ok.

That said, normally I would not do this. My preference is to only use normal serialization either within a single process, or between two processes are on the same machine and getting the serialized classes out of the same jar file. If that's not the case, serializing to XML is the better and safer choice.

like image 119
Paul Tomblin Avatar answered Jan 01 '23 19:01

Paul Tomblin


Along with the serialVersionUID the package structure has to remain consistent for serialization, so if you had myjar.mypackage.myclass in 1.4 you have to have myjar.mypackage.myclass in 1.6.

It is not uncommon to have the Java version or your release version somewhere in the package structure. Even if the serialVersionUID remains the same between compilations the package structure will cause an incompatible version exception to get thrown at runtime.

BTW if you implement Serializable in your classes you should get a compiler warning if serialVersionUID is missing.

In my view (and based on some years of quite bitter experience) Java native serialization is fraught with problems and ought to be avoided if possible, especially as there is excellent XML/JSON support. If you do have to serialize natively, then I recommend that you hide your classes behind interfaces and implement a factory pattern in the background which will create an object of the right class when needed.

You can also use this abstraction for detecting the incompatible version exception and doing whatever conversion is necessary behind the scenes for migration of the data in your objects.

like image 25
Simon Avatar answered Jan 01 '23 20:01

Simon