3

core java volumeII chapter II says, unlike readObject/writeObject, readExternal/writeExternal are able to save and restore data including the super class. I just did an experiment, and seems readObject/writeObject could do the same work:

class base implements Serializable{
    protected String field = "xyz";
}
class c1 extends base implements Serializable {
    private String name = "name";
    private int age = 12;

    private void readObject(ObjectInputStream ois) {
        System.out.println("readObject!!");
        try {
            field = (String) ois.readObject();
            name = (String) ois.readObject();
            age = ois.readInt();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void writeObject(ObjectOutputStream oos) {
        System.out.println("writeObject!!");
        try {
            oos.writeObject(field);
            oos.writeObject(name);
            oos.writeInt(age);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

My question is: when should we need to use readExternal/writeExternal()? I don't see any work that readExternal/writeExternal could do while readObject/writeObject could not.

Please kindly help to clarify. Thanks a lot.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • Related [What is the difference between Serializable and Externalizable in Java?](https://stackoverflow.com/questions/817853/what-is-the-difference-between-serializable-and-externalizable-in-java) – Naman Nov 25 '18 at 06:19

1 Answers1

3

Both Serializable and Extenalizable are used to serialize or persist java objects but the way they do is differs. In case of Serializable Java Virtual machine has full control for serializing object while in case of Externalizable, application gets control for persisting objects. writeExternal() and readExternal() method provides complete control on format and content of Serialization process to application which can be leveraged to increase performance and speed of serialization process.

joemokenela
  • 299
  • 1
  • 9
  • 1
    Thanks, but seems my question is not answered. My confuse is, is there anything that read/writeObject cannot do, so we "need" read/writeExternal() functions? – Troskyvs Nov 24 '18 at 13:00
  • read/WriteObject can do everything, Just that you want to use read/writeExternal when you want more control over the serialization logic. – joemokenela Nov 24 '18 at 16:11