Java的对象序列化实现了Serializable接口的对象转换成一个字节序列,并且可以以后将这个字节完全恢复为原来的对象;
这样的步骤可以通过网络进行,也就是说,对象序列化机制可以自动弥补不同操作系统之间的差异;
使用对象序列化传递的过程:将对象构造时的必要字段写转化为字节序列,写入文件,读取字节序列后,将其转化为必要字段,调用class的构造方法使用这些必要字段构建新对象;
class Person implements Serializable{
int id;
String name;
transient String password;
//transient瞬关键字,关键字逐个字段关闭序列化,即不保存和恢复该数据,用于防止对象的敏感部分被序列化;
public Person(int id,String name,String password){
this.id = id;
this.name = name;
this.password = password;
}
}
static void main() throws ClassNotFoundException,IOException{
Person person = new Person(1234,"assad","password");
//通过序列化写入对象
ObjectOutputStream out = new ObjetcOutputStream("person.dat");
out.writeObject(person);
out.close();
//通过序列化读取对象
ObjectInputStream in = new ObjectInputStream("person.dat");
Person person = (Person)(in.readObject());
in.close();
}
/*in:
Person
id = 1234
name = assad
password = null*/
Enternalizable继承了Serializable对象,并且添加了2个方法**writeEnternal()和readEnternal()方法,这2个方法会在对象序列化和反序列化过程中被自动调用**;
class Person implements Enternalizable{
int id;
String password;
public Person(int id,String password){
this.id = id;
this.password = password;
}
public void writeObject(ObjectOutput out) throws IOException{
out.writeInt(id);
out.wrireObject(password);
}
public void readObject(ObjectInput in) throws IOException,ClassNotFoundException{
id = in.readInt();
password = (String)in.readObject();
}
}
static void main() throws ClassNotFoundException,IOException{
Person person = new Person(1234,"assad","password");
//通过序列化写入对象
ObjectOutputStream out = new ObjetcOutputStream("person.dat");
out.writeObject(person);
out.close();
//通过序列化读取对象
ObjectInputStream in = new ObjectInputStream("person.dat");
Person person = (Person)(in.readObject());
in.close();
}