Howto deserialize class, if class version was changed-Collection of common programming errors
You won’t be able to perform the cast in the last line, because it’s of a different class (which is not castable) – you might get a confusing message such as test.SerObj is not an instance of test.SerObj.
This arises from the fact that a class is essentially a java.lang.Class instance, which critically is unique within a given classloader. Even if you referenced the exact same *.class file, an instance of SerObj loaded by the default classloader is a different class from an instance of SerObj loaded by clazLader. Neither class could be cast to the other one.
Thus it is not going to be possible for the method to return SerObj if you need to use multiple classloaders to deserialise. (Besides – how could it, when the two class files could have arbitrary differences?)
One possible workaround is to define an interface that defines the behaviour which is fixed between versions of the class. If you set up the temporary classloader such that it can only load SerObj from the oldversion class file, and that it has the right parent classloader, then your old SerObj should still implement the interface class as defined by the root classloader.
In this was, both the new SerObj and old SerObj instances would be castable to the SerObjIface interface, and so you could declare your method to return that. And in fact if you want callers to deal with different yet similar classes (which is what different versions of “the same class” are), you should arguably be returning an interface for this anyway.