Java Serialization - Incompatible serialVersionUID

I understand the theory of incompatible serialVersionUIDs (i.e. you can distinguish different compilation versions of the same class), but I see a problem that I donโ€™t understand and do not fall into the obvious causes of the error (another compiled version is the same class).

I am testing the serialization / deserialization process. All code runs on the same machine, in the same virtual machine, and both serialization and deserialization methods use the same version of the compiled class. Serialization is working fine. The serial class is quite complex, contains a number of other classes (Java and UDT types) and contains reference loops. I did not declare my own UID in any class.

This is the code:

public class Test { public static void main(String[] args) throws Exception { ContextNode context = WorkflowBuilder.getSimpleSequentialContextNode(); String contextString = BinarySerialization.serializeToString(context); ContextNode contextD = BinarySerialization.deserializeFromString(ContextNode.class, contextString); } } public class BinarySerialization { public static synchronized String serializeToString(Object obj) throws Exception { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(byteStream); oos.writeObject(obj); oos.close(); return byteStream.toString(); } public static synchronized <T> T deserializeFromString(Class<T> type, String byteString) throws Exception { T object = null; ByteArrayInputStream byteStream = new ByteArrayInputStream(byteString.getBytes()); ObjectInputStream in = new ObjectInputStream(byteStream); object = (T)in.readObject(); in.close(); return object; } } 

I get an InvalidClassException (local class incompatible: stream classdesc serialVersionUID = -7189235121689378989, local class serialVersionUID = -7189235121689362093) when deserializing.

What is the main problem? And how to fix it?

thanks

Edit I must indicate the purpose of this. Serialized data must be stored in the sqlite database and sent over the network to other clients. If String is the wrong format for transmitting serialized data, what should I use instead, will this allow me to store and transmit data? Thanks again.

+4
source share
1 answer

First rule: never use String or char[] or Reader or Writer when processing binary data.

You process binary data and try to put it in a String . Do not do this, which is essentially a broken operation.

Next: the return value of byteStream.toString() no way reflects the actual contents of ByteArrayOutputStream . You will want to use .getBytes() and pass byte[] around (remember: treat binary data as binary data, not as String ).

+12
source

All Articles