Fuad Malikov
Fuad Malikov

Reputation: 2355

How to override Externalizable to Serializable?

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?

Upvotes: 3

Views: 436

Answers (1)

AlexR
AlexR

Reputation: 115378

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 method writeObjectOverride() that can be overridden by subclass of ObjectOutputStream.

So, the solution is the following. Create subclass of ObjectOutputStream that implements writeObjectOverride() as following:

protected void writeObjectOverride(Object obj) throws IOException {
    if (isMySpecialClass(obj.getClass())) {
        // call writeOrdinaryObject(obj, desc, unshared); using reflection because this method is private
        return;
    }
    // fall back to regular mechanism.
}

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 Serializable instead of Externalizable. But I personally like the first way more.

Upvotes: 1

Related Questions