Main类
public class Main {
public static void main(String[] args) {
Person pA = new Person("zhao", 18, new Person("peng", 30, null));
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(pA);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis)) {
Person pB = (Person) ois.readObject();
pA.setFriend(new Person("li", 26, null));
System.out.println(pA.toString() + " " + pA.friend.hashCode());
System.out.println(pB.toString() + " " + pB.friend.hashCode());
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Person类
public class Person implements Serializable {
String name;
int age;
Person friend;
public Person(String name, int age, Person friend) {
this.name = name;
this.age = age;
this.friend = friend;
}
public void setFriend(Person friend) {
this.friend = friend;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", friend=" + friend +
'}';
}
}
结果
Person{name='zhao', age=18, friend=Person{name='li', age=26, friend=null}} 1791741888
Person{name='zhao', age=18, friend=Person{name='peng', age=30, friend=null}} 1595428806