package com.test.myjava; //主要演示了Serializable接口以及transient关键字 import java.io.*; class Information implements Serializable{} public class SerializableTest implements Serializable{ private int id; private transient String password; private String name; private Information otherInformation; public SerializableTest(int i,String p,String n,Information f){ System.out.println("Constructor:"+n); id = i; password = p; name = n; otherInformation = f; } public String toString(){ return "id:"+id +" name:"+name +" pasword:"+password //密码没有保存,为null +" friendName:"+otherInformation;//otherInformation.hashCode() } public static void main(String[] args ) throws IOException,ClassNotFoundException{ Information allFriendName = new Information(); SerializableTest user1 = new SerializableTest(1,"1","user1",allFriendName); SerializableTest user2 = new SerializableTest(2,"2","user2",allFriendName); SerializableTest user3 = new SerializableTest(3,"3","user3",allFriendName); System.out.println("Start\n"); System.out.println(user1.toString()); System.out.println(user2.toString()); System.out.println(user3.toString()); //序列化 ByteArrayOutputStream buf1 = new ByteArrayOutputStream(); ObjectOutputStream out1 = new ObjectOutputStream(buf1); out1.writeObject(user1); out1.writeObject(user2); ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); ObjectOutputStream out2 = new ObjectOutputStream(buf2); out2.writeObject(user3); //恢复 ObjectInputStream in1 = new ObjectInputStream( new ByteArrayInputStream(buf1.toByteArray())); ObjectInputStream in2 = new ObjectInputStream( new ByteArrayInputStream(buf2.toByteArray())); user1 = (SerializableTest)in1.readObject(); user2 = (SerializableTest)in1.readObject(); user3 = (SerializableTest)in2.readObject(); System.out.println("Then\n"); System.out.println(user1.toString()); System.out.println(user2.toString()); System.out.println(user3.toString()); } }
输出结果:
Constructor:user1 Constructor:user2 Constructor:user3 Start id:1 name:user1 pasword:1 friendName:com.test.myjava.Information@c17164 id:2 name:user2 pasword:2 friendName:com.test.myjava.Information@c17164 id:3 name:user3 pasword:3 friendName:com.test.myjava.Information@c17164 Then id:1 name:user1 pasword:null friendName:com.test.myjava.Information@19b49e6 id:2 name:user2 pasword:null friendName:com.test.myjava.Information@19b49e6 id:3 name:user3 pasword:null friendName:com.test.myjava.Information@10d448