gpt4 book ai didi

java - ObjectOutputStream 的对象如何调用 Serialized 对象的私有(private) writeObject 方法

转载 作者:行者123 更新时间:2023-12-02 07:43:35 25 4
gpt4 key购买 nike

当我运行这个演示时,它会调用 TestBean 的私有(private) 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();
}
}
}

最佳答案

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

使用反射可以调用私有(private)方法。如果您在 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);
}

关于java - ObjectOutputStream 的对象如何调用 Serialized 对象的私有(private) writeObject 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11238593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com