“对象序列化”是什么意思?你能用一些例子解释一下吗?
原文由 Warrior 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以将序列化视为将对象实例转换为字节序列(根据实现可能是二进制或非二进制)的过程。
当你想通过网络传输一个对象数据时,它非常有用,例如从一个 JVM 到另一个。
在 Java 中,序列化机制内置于平台中,但您需要实现 Serializable 接口才能使对象可序列化。
您还可以通过将属性标记为 transient 来防止对象中的某些数据被序列化。
最后你可以覆盖默认机制,并提供你自己的;这可能适用于某些特殊情况。为此,您可以使用 java 中的隐藏功能之一。
重要的是要注意,被序列化的是对象的“值”或内容,而不是类定义。因此方法没有序列化。
这是一个非常基本的示例,带有注释以方便阅读:
import java.io.*;
import java.util.*;
// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {
// These attributes conform the "value" of the object.
// These two will be serialized;
private String aString = "The value of that string";
private int someInteger = 0;
// But this won't since it is marked as transient.
private transient List<File> unInterestingLongLongList;
// Main method to test.
public static void main( String [] args ) throws IOException {
// Create a sample object, that contains the default values.
SerializationSample instance = new SerializationSample();
// The "ObjectOutputStream" class has the default
// definition to serialize an object.
ObjectOutputStream oos = new ObjectOutputStream(
// By using "FileOutputStream" we will
// Write it to a File in the file system
// It could have been a Socket to another
// machine, a database, an in memory array, etc.
new FileOutputStream(new File("o.ser")));
// do the magic
oos.writeObject( instance );
// close the writing.
oos.close();
}
}
当我们运行这个程序时,文件“o.ser”被创建,我们可以看到后面发生了什么。
如果我们将 someInteger 的值更改为,例如 Integer.MAX_VALUE ,我们可以比较输出以查看不同之处。
下面是一个截屏,准确地显示了这种差异:
你能找出不同之处吗? ;)
Java 序列化中还有一个额外的相关字段: serialversionUID ,但我想这已经太长了,无法涵盖它。
原文由 OscarRyz 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
序列化是将对象转换为一系列字节,以便可以轻松地将对象保存到持久存储或通过通信链路进行流式传输。然后可以反序列化字节流——将其转换为原始对象的副本。