如何通过ObjectOutputStream的对象调用Serializable对象的私有writeObject方法 [英] How private writeObject method of Serializable object called by object of ObjectOutputStream

查看:183
本文介绍了如何通过ObjectOutputStream的对象调用Serializable对象的私有writeObject方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When i run this demo it's call TestBean's writeObject method which is private

怎么可能?

以下是代码:

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();
        }
    }
}


推荐答案

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

If your serializable object has any writeObject method, it will be called otherwise the defaultWriteObject method will be called.

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

The private method calling is possible using the reflection. If you see the source code of ObjectOutputStream Class in that method writeSerialData, the code below answers your question.

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);
}

这篇关于如何通过ObjectOutputStream的对象调用Serializable对象的私有writeObject方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆