Hi I have classes that extend some given interfaces which I can’t change. And those interfaces implement Externalizable. But I want to serialize my objects using regular Java serialization.
Basically I want the serialization to ignore Externalizable and use Serializable only
Any ways to do this?
Yes, you can if you control the OutputStream creation.
Typically we use
ObjectOutputStream.writeObject()to write serializable objects. This method checks flag ‘enableOverride’. If the flag is true it calls methodwriteObjectOverride()that can be overridden by subclass ofObjectOutputStream.So, the solution is the following. Create subclass of
ObjectOutputStreamthat implementswriteObjectOverride()as following:As you can see from the comment you will have to call some methods of base class using reflection because they are private (do not forget call
setAccessible(true)). But it is possible. I believe that this task could be done withing a couple of hours.Good luck.
BTW yet another solution is using bytecode modification. You can modify the byte code on the fly using various libraries, so make class to implement
Serializableinstead ofExternalizable. But I personally like the first way more.