父类未实现序列化 To allow subtypes of non-serializable classes to be serialized, the * subtype may assume responsibility for saving and restoring the * state of the supertype's public, protected, and (if accessible) * package fields. The subtype may assume this responsibility only if * the class it extends has an accessible no-arg constructor to * initialize the class's state. It is an error to declare a class * Serializable if this is not the case. The error will be detected at * runtime. <p>
The subtype may assume this responsibility only if * the class it extends has an accessible no-arg constructor to * initialize the class's state.
也就是说需要父类要有无参的构造方法。
我们试一下如果是没有父类无参的构造函数会怎么样
因为父类如果没有写构造函数的话,默认会有一个无参的构造函数,所以我们这样写
第一种情况 父类没有无参的构造函数
父类:
public class BaseBean {
public String property1;
public String property2;
public BaseBean(String id){
}
}
子类
public class TestBean extends BaseBean implements Serializable{
public String desc;
public static final int serialVersionUID = 1;
public TestBean(String id) {
super(id);
}
@Override
public String toString() {
return "TestBean{" +
"desc='" + desc + '\'' +
", property1='" + property1 + '\'' +
", property2='" + property2 + '\'' +
'}';
}
}
这个时候序列化的过程没有出什么问题,但是反序列的时候开始报错了
//序列化之后通过给父类再加上默认构造方法,这个时候反序列化可以看到其实即便父类没有默认构造参数,序列化的过程也是
成功了的。但是1,不能反序列化,2,父类的属性没有序列化到,只序列化了子类的属性
java.io.InvalidClassException: calc.superdy.ttest.test.TestBean; no valid constructor
第二种情况 父类有无参构造
通过上面的例子,可以知道,如果父类没有无参构造函数,则序列化过程不能成功
下面加下无参构造,看下情况
public class BaseBean {
public String property1;
public String property2;
public BaseBean(String id){
}
public BaseBean(){}
}
public class TestBean extends BaseBean implements Serializable{
public String desc;
public static final int serialVersionUID = 1;
public TestBean(String id) {
super(id);
}
@Override
public String toString() {
return "TestBean{" +
"desc='" + desc + '\'' +
", property1='" + property1 + '\'' +
", property2='" + property2 + '\'' +
'}';
}
}
public void serialization(View view) {
try {
TestBean testBean = new TestBean("");
testBean.property1 = "属性88999988";
testBean.property2 = "属性88999988";
testBean.desc = "我是testbean88999988";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("/sdcard/aaatest.txt"));
objectOutputStream.writeObject(testBean);
} catch (IOException e) {
e.printStackTrace();
}
}
public void deserialization(View view) {
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream("/sdcard/aaatest.txt"));
TestBean testBean = (TestBean) objectInputStream.readObject();
Log.i(TAG,"deserialization"+testBean.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
这个时候打印结果为:
deserializationTestBean{desc='我是testbean88999988', property1='null', property2='null'}
也就是说,虽然可以序列化反序列化成功,但是父类的属性其实并没有参与到序列化反序列化的过程中来