ObjectOutputStream 的对象如何调用 Serialized 对象的私有 writeObject 方法

che*_*tan 2 java serialization

当我运行这个演示时,它调用 TestBean 的writeObject私有方法

这怎么可能 ?

这是代码:

import java.io.FileOutputStream;

public class Test {

    public static void main(String[] args) {

        try {
            TestBean testBean = test.new TestBean();

            testBean.setSize(23);
            testBean.setWidth(167);

            FileOutputStream fos =
                new FileOutputStream(new File("d:\\serial.txt"));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(testBean);

            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class TestBean implements Serializable {

        private static final long serialVersionUID = 1L;

        private int size;
        private int width;

        public int getSize() {
            return size;
        }

        public void setSize(int size) {
            this.size = size;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        private void writeObject(ObjectOutputStream out) throws IOException {
            System.out.println("TestBean writeObject");
            out.defaultWriteObject();
        }

        private void readObject(ObjectInputStream input) throws IOException,
                                                                ClassNotFoundException {
            System.out.println("TestBean readObject ===================> ");
            input.defaultReadObject();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sya*_*yam 7

如果您的可序列化对象具有任何 writeObject 方法,则会调用该方法,否则将调用 defaultWriteObject 方法。

使用反射可以调用私有方法。如果您在 writeSerialData 方法中看到 ObjectOutputStream 类的源代码,下面的代码可以回答您的问题。

if (slotDesc.hasWriteObjectMethod()) {
 // through reflection it will call the Serializable objects writeObject method
} else {
// the below is the same method called by defaultWriteObject method also.
writeSerialData(obj, desc);
}
Run Code Online (Sandbox Code Playgroud)