序列化
序列化就是将一个对象转换成字节序列,方便存储和传输。
- 序列化:ObjectOutputStream.writeObject()
- 反序列化:ObjectInputStream.readObject()
不会对静态变量进行序列化,因为序列化只是保存对象的状态,静态变量属于类的状态。
Serializable
序列化的类需要实现 Serializable 接口,它只是一个标准,
没有任何方法需要实现,但是如果不去实现它的话而进行序列化,会抛出异常。
/*** 序列化就是将一个对象转换成字节序列,方便存储和传输。- 序列化:ObjectOutputStream.writeObject()- 反序列化:ObjectInputStream.readObject()*/public class SerializableDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {String objectFile="demo6.txt";//序列化serialize(objectFile);//反序列化deserialize(objectFile);}//序列化public static void serialize(String objectFile) throws IOException {A a=new A(1,"aaa");ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(objectFile));//序列化objectOutputStream.writeObject(a);objectOutputStream.close();}//反序列化public static void deserialize(String objectFile) throws IOException, ClassNotFoundException {ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(objectFile));A a2=(A)objectInputStream.readObject();System.out.println(a2);objectInputStream.close();}private static class A implements Serializable {private int x;private String y;A(int x, String y) {this.x = x;this.y = y;}@Overridepublic String toString() {return "x = " + x + " " + "y = " + y;}}}
输出结果:
x = 1 y = aaa
transient
transient 关键字可以使一些属性不会被序列化。
ArrayList 中存储数据的数组 elementData 是用 transient 修饰的,因为这个数组是动态扩展的,并不是所有的空间都被使用,因此就不需要所有的内容都被序列化。通过重写序列化和反序列化方法,使得可以只序列化数组中有内容的那部分数据。
private static class A implements Serializable {private int x;private transient String y; //transient 关键字可以使一些属性不会被序列化。A(int x, String y) {this.x = x;this.y = y;}@Overridepublic String toString() {return "x = " + x + " " + "y = " + y;}}
输出结果:
x = 1 y = null
