Last mod: 2024.12.14
Java - Serial Version UID
The serialVersionUID field and its usage should be familiar to every Java programmer. It is used to verify the uniqueness of class, which is used, among others, in serialization and desrialization of objects. In most situations we don't even have to think about it. The problem occurs when in more complex projects serialized classes have different Serial Version UID and application terminates with exception "java.io.InvalidClassException ... local class incompatible: stream classdesc serialVersionUID ...".
Basic example
To add a unique Serial Version UID number we need to add a constant "private static final long serialVersionUID" in the example class code:
public class User implements Serializable {
private static final long serialVersionUID = 123_456_678L;
public String login;
public String email;
}
Checking the serialVersionUID in the java application
We can check autogenerated or declared serialVersionUID programmable from a java application:
// Replace 'YourExampleClass.class' with the class you want to inspect
ObjectStreamClass osc = ObjectStreamClass.lookup(YourExampleClass.class);
if (osc != null) {
long serialVersionUID = osc.getSerialVersionUID();
System.out.println("Generated serialVersionUID: " + serialVersionUID);
} else {
System.out.println("Class is not serializable.");
}
Checking the serialVersionUID from bash
// Replace 'your.package.YourExampleClass' with the class you want to inspect
serialver your.package.YourExampleClass
We can use additional options:
- -classpath path-files - Sets the search path for application classes and resources. Separate classes and resources with a colon (:).
Class search
Sometimes it is necessary to find appropriate classes in packed jar archives. For example, to find several versions of the same class (exception related to different serialVersionUID). Here we can use the command:
// Replace 'YourExampleClass.class' with the class you want to inspect
sudo find / -type f -name "*.jar" -exec sh -c 'unzip -l "{}" | grep "YourExampleClass.class" && echo "Found in: {}"' \;
Links
https://docs.oracle.com/javase/8/docs/platform/serialization/spec/class.html
https://docs.oracle.com/en/java/javase/11/tools/serialver.html