views:

84

answers:

3

My friend asked me if we serialize an object in java 1.5 and then deserialize it back in java 1.6 then it will throw an exception. What is that exception and why that is thrown?

But i doubt there will be any exception. Reason being nothing is changed in class definition, so it should not face any problem in rebuilding the object back from the serialized form. Am i right? If not, then what and why the exception is thrown?

Note: The class remains untouched not any field, not methods and not serialVersionUID is changed.

+5  A: 

The serialization format has a detailed specification, which is changed only to accomodate new language features (such as enums in Java 5), and I'm pretty sure any such changes are carefully made downwards-compatible.

So unless you encounter a bug (which is certainly possible) or try to deserialize something with a Java version where some features did not exist yet, deserialization should work across different Java versions, vendors and platforms.

Michael Borgwardt
i would like to accept this. But let's see if get another answer :)
Rakesh Juyal
+2  A: 

Michael's answer is mostly correct. But there are some (admittedly contrived) cases where serialized versions are not forward compatible.

I doubt there would be any forward-compatibility problems among classes that do not have writeObject, readObject, readObjectNoData methods. I doubt that there are any non-contrived cases among those that do.

class Anti6 implements Serializable
{
       private void writeObject(java.io.ObjectOutputStream out)
       throws IOException { }

       private void readObject(java.io.ObjectInputStream in)
       throws IOException, ClassNotFoundException
       {
             readObjectNoData ( ) ;
       }

       private void readObjectNoData()
       throws ObjectStreamException
       {
             if ( System . getProperty ( "java.version" ) . equals ( "1.6" ) )
             { throw new RuntimeException ( "I Hate 1.6" ) ; }
       }
}
emory
i like it ;) +1
Rakesh Juyal
A: 

The serialised objects have something like minor and major version numbers, which tells about the compatibility of that object. However, the serialisation should be backward compatible. So objects serialised with 1.5 should work with 1.6.

If you try to load same object in 1.4, you should see the same exception as the exception thrown when class compiled in 1.5 is run in 1.4 runtime.

Dhana
I didn't see anything about minor and major version numbers in http://download.oracle.com/javase/6/docs/platform/serialization/spec/serialTOC.html. Where did u see that?
emory
I think its part of Magic content ... http://download.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html
Dhana