系列文章目录
一、是什么?
然后进行序列化
运行后我们发现报错了
说明一个问题
虽然Husband实现了Serializable,但是因为在序列化Husband过程中,包含wife对象,所以要求Wife类也要实现Serializable接口
二、问题二
为什么会出现这个问题
打印 自动调用 toString对象
死循环了
怎么解决呢?
解决办法:
Wife类也一样修改一下,这样就不会死循环了
总结
在序列化Husband对象,要求Wife序列化。
String类型也实现序列化接口
1、序列化一个对象时,要求它的属性要么是基本数据类型,如果是引用数据类型,这个引用数据类型也必须实现Serializable接口。
2、序列化一个数组,要求元素类型实现Serializable接口。
完整代码:
package com.atguigu.test03;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Test;
public class Test01序列化 {
@Test
public void test2() throws IOException, ClassNotFoundException{
//反序列化Husband
FileInputStream fis=new FileInputStream("marry.dat");
ObjectInputStream ois= new ObjectInputStream(fis);
Object o=ois.readObject();
Husband h=(Husband)o;
System.out.println(h);
}
@Test
public void test1() throws IOException{
//序列化Husband
Husband h = new Husband();
Wife w=new Wife();
h.setName("李亮");
w.setName("瞿月娇");
h.setWife(w);
w.setHusband(h);
FileOutputStream fos = new FileOutputStream("marry.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(h);
oos.close();
fos.close();
}
}
Husband类:
package com.atguigu.test03;
import java.io.Serializable;
public class Husband implements Serializable {
private static final long serialVersionUID=1L;
private String name;
private Wife wife;
public Husband() {
super();
}
public Husband(String name, Wife wife) {
super();
this.name = name;
this.wife = wife;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
@Override
public String toString() {
return "Husband [name=" + name + ", wife=" + wife.getName() + "]";
}
}
Wife类
package com.atguigu.test03;
import java.io.Serializable;
public class Wife implements Serializable{
private static final long serialVersionUID=1L;
private String name;
private Husband husband;
public Wife() {
super();
}
public Wife(String name, Husband husband) {
super();
this.name = name;
this.husband = husband;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Husband getHusband() {
return husband;
}
public void setHusband(Husband husband) {
this.husband = husband;
}
@Override
public String toString() {
return "Wife [name=" + name + ", husband=" + husband.getName() + "]";
}
}