I’m new to serialization, so this might be a simple question, but my google-fu is weak today.
Suppose you have the following classes:
public class Base implements Serializable {
// ...
}
public class Der1 extends Base {
// ...
}
public class Der2 extends Base {
// ...
}
Alice randomly creates an object of either Der1 or Der2, serializes it to a file, and sends it to Bob. Bob knows this object’s class is a subclass of Base, but doesn’t know which one (he has the same class definitions that Alice has). How can Bob deserialize the file to be an instance of the proper subclass?
My first thought was that Alice could define a class like this:
public DerClass implements Serializable {
public Class<? extends Base> class;
}
She uses this to store the object’s class, serializes it and sends it to Bob. Bob constructs a DerClass object from this file, reads the class variable, uses it to instantiate the proper subclass, and reads the serialized object into it. Would this work? Is there a better way?
The deserializing application doesn’t need to know the type, it only needs to have the same class available in the class path. e.g. Alice need to have all the classes Bob might send and their parents and dependants.