Java specification stats that
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.
enter code here
But If I assign all the classes same serial version id as follows
static final long serialVersionUID = 1L;
Now all my classes will have same serialversionUID and this will never result in InvalidclassException.
I know that we give it explicitly so that its value remains constant across different JVM implementations.
Please let me know what is the use of putting same id for all the classes and what will happen if we modify class in between serialization and deserialization ?
I believe the serialVersionUID
is only used to determine the version of that class that has been serialized - the class name is always present too, so it won't lead to any ambiguity.
Please let me know what is the use of putting same id for all the classes
They're effectively unrelated values. It's just simple to use 1 and increment it every time you make a breaking change.
what will happen if we modify class in between serialization and deserialization ?
That entirely depends on the type of modification you make. If you're just adding or removing methods, or static fields, it's fine - that wouldn't affect the serialized data anyway. If you make any changes to instance fields, that's when life gets hairy. You'd need to study the serialization format in detail to work out exactly what would constitute a breaking change, but it's entirely possible that just changing the name of a field could break things - e.g. if fields are serialized in name order.
You might want to consider using a binary data format which plays a bit more pleasantly with data format changes, such as Protocol Buffers. (There are other benefits available too, such as portability and speed - and protobuf isn't the only game in town, either.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With