在现实应用中,我们常常需要将对象及其状态在多个应用之间传递、共享,或者将对象及其状态持久化,在其他地方重新读取被保存的对象及其状态继续进行处理。这就需要通过将Java对象序列化来实现。
在使用Java 序列化技术保存对象及其状态信息时,对象及其状态信息会被保存在一组字节数组中,在需要时再将这些字节数组反序列化为对象。注意,对象序列化保存的是对象的状态,即它的成员变量,因此类中的静态变量不会被序列化。
对象序列化除了用于持久化对象,在RPC(远程过程调用)或者网络传输中也经常被使用。
注意事项:
类要实现序列化功能,需要实现java.io.Serializable接口;序列化和反序列化的的ID需要一致,通常使用private static final long serialVersionUID定义序列化ID;序列化不会保存静态变量;需要序列化父类变量时,父类也需要实现java.io.Serializable接口;使用Transient关键字会阻止变量被序列化,反序列化时,变量被设置为对应类型的初始值;
代码实现
public class User implements Serializable {
private static final long serialVersionUID = 1;
public User(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private transient int age;
private static int weight = 100;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static int getWeight() {
return weight;
}
public static void setWeight(int weight) {
User.weight = weight;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\file\user.txt"));
out.writeObject(new User("name", 18));
out.flush();
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\file\user.txt"));
User user = (User) in.readObject();
System.out.println("name=" + user.getName() + "n" + "age=" + user.getAge() + "n" + "weight=" + User.getWeight());
in.close();
}
}



