I have a class that is something like the following:
public class Foo {
static byte[] convertToArray(Foo f);
static Foo convertToFoo(byte[] ba);
}
How can I use convertToArray and convertToFoo to allow Foo to implement java.io.Serializable? The default serialization procedure doesn’t seem like a good solution for my class because it would require changing a lot of other classes to implement Serializable. However, I already have a way to go to and from bytes, so there should be an easy way for Foo to implement serializable without having to declare all dependent members as Serializable. I suspect overriding readObject and writeObject is the way to go, but what is the correct way to do this, since these are instance methods with return type void?
Check out Externalizable, which is a subinterface of Serializable. Its
readExternalandwriteExternalmethods delegate the serialization details to the programmer, which sounds appropriate in your case.During deserialization (in your implementation of
readExternal), you will need to useFoo.convertToFooto convert the bytes from anObjectInputto aFooobject, and then copy all of the state of thatFooobject intothis.A snippet from the Javadoc that describes the semantics of Externalizable: