小编典典
你可以将序列化视为将对象实例转换为字节序列(取决于实现的二进制或非二进制)的过程。
当你要通过网络传输一个对象数据(例如从一个JVM传输到另一个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 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,则可以比较输出以查看差异。
2020-02-26