简体   繁体   中英

Reusing the Java (de)serialization in implementing Externalizable

I would like to implement java.io.Externelizable that essentially says do whatever java.io.Serializable would do with some modifications. What hooks, if any, are there into the Java serialization mechanism? Alternatively are there any external libraries that accurately emulate the Java serialization mechanism in an open/extensible way?

You don't need to implement java.io.Externalizable for small customizations to serialization. Just implement java.io.Serializable as before and implement the following two methods in the class:

private void writeObject(ObjectOutputStream oos) {
    oos.defaultWriteObject();
    // custom serialization
    oos.writeInt(notSerializableObj.getId());
}

private void readObject(ObjectInputStream ois) {
    ois.defaultReadObject();
    // custom de-serialization
    notSerializableObj = new NotSerializableObj(ois.readInt());
}

java.io.Externalizable is mostly used when you want to completely change the way your object is serialized (the underlying algorithm itself) for performance or security reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM