java - writeObject 和 readObject 如何工作?

标签 java serialization java-custom-serialization

<分区>

当我阅读JDK 6.0 的源代码时,我在ArrayList 中找到了这两个方法。你看他们都是私有(private)的。但是经过搜索,我没有找到任何其他方法调用它们中的任何一个。我也考虑过本地方法,但仍然找不到。这两个方法看似处理IO,但从来没有被调用过。

那么,我的问题是,它们是如何工作的?还有其他调用私有(private)方法的方法吗?

/**
 * Save the state of the <tt>ArrayList</tt> instance to a stream (that is, serialize it).
 */
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException;

/**
 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, deserialize it).
 */
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException;

最佳答案

这两个方法在可序列化类中用于自定义序列化(aka Customize the Default Protocol)

文章正文:

There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

  1. private void writeObject(ObjectOutputStream out) throws IOException;
  2. private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can.

关于java - writeObject 和 readObject 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12189221/

相关文章:

java - 如何告诉 gradle 在构建时在项目中安装 npm?

java - 如何在不实际序列化对象的情况下估计 Java 中对象的序列化大小?

java - 使用 ReadObject 和 WriteObject 的自定义序列化

java - 在ArrayList中存储不同类的对象

java - 如何使用字符串作为输入创建并输出日期对象?即 "13/04/1998"

serialization - GWT 序列化问题

java - 自定义 BeanPropertyFilter - 仅序列化字符串的一部分

java - 计算链表中的所有节点

c# - 如何检查 Json 是否匹配特定的 C# 类型?