gpt4 book ai didi

java - java序列化的内部原理: Which class initiates Serialization process?

转载 作者:行者123 更新时间:2023-12-01 21:56:07 25 4
gpt4 key购买 nike

如果我想序列化一个java对象,我只需要实现标记接口(interface)Serializable ,它没有任何方法。

class Employee implements Serializable{
private int id;
private String name;

/*
private void writeObject(ObjectOutputStream out) throws IOException{
System.out.println("in write object");
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
System.out.println("in read object");
}
*/

}

我的查询(编辑):

  1. 通过实现标记接口(interface)Serializable在我的代码中,Java 正在序列化我的对象。哪个类负责实现 Serializable 的 java 对象序列化界面 ?

    这个过程的入口点是什么?谁调用ObjectOutputStream?

  2. 即使没有实现 Externalizable接口(interface),我的类的私有(private)方法:readObjectwriteObject已被调用。这些已在上面的代码中进行了注释,以启用默认的 Java 序列化。为什么在没有明确实现 Externalizable 的情况下首先允许它接口(interface)?

编辑:为了让我的问题清楚,为什么Java允许私有(private)readObject & writeObject方法而不是强制使用 Externalizable实现自定义序列化过程。

来自 Java 文档:

The writeExternal and readExternal methods of the Externalizable interface are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state. These methods supersede customized implementations of writeObject and readObject methods.

这两种机制没有达到相同的结果吗?

最佳答案

负责序列化对象的类是java.io.ObjectOutputStream。反序列化是在 java.io.ObjectInputStream 类中完成的。

ObjectOutputStream 类的 JavaDoc 还包含以下内容:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException;
private void readObjectNoData()
throws ObjectStreamException;

下面是一些伪代码,显示了 ObjectOutputStream 的工作原理。我省略了很多细节,部分工作是在 ObjectStreamClass 中完成的。

class ObjectOutputStream {

writeObject(obj) {
writeObject0(obj);
}

writeObject0(obj) {
if (hasWriteReplaceMethod(obj)) {
obj = obj.writeReplace();
}
writeOrdinaryObject(obj);
}

writeOrdinaryObject(obj) {
if (isExternalizable(obj)) {
writeExternalData(obj);
} else {
writeSerialdata(obj);
}
}

writeExternalData(obj) {
obj.writeExternal(this);
}

writeSerialData(obj) {
if hasWriteObjectMethod(obj)
obj.writeObject(this);
else
defaultWriteFields(obj);
}
}

关于java - java序列化的内部原理: Which class initiates Serialization process?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253236/

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