J2SE中的序列化是将对象转换成字节流,用于对象的存储和传输。而在序列化对象时,如果该对象实现了Serializable接口,那么子类也会自动实现序列化,这就是所谓的“继承序列化”。
下面通过示例说明继承序列化的几个要点:
1.子类序列化时父类属性的序列化与反序列化:
public class Parent implements Serializable{
private static final long serialVersionUID = 1L;
private int parentId;
public Parent(int parentId) {
this.parentId = parentId;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
}
public class Child extends Parent {
private static final long serialVersionUID = 1L;
private int childId;
public Child(int parentId, int childId) {
super(parentId);
this.childId = childId;
}
public int getChildId() {
return childId;
}
public void setChildId(int childId) {
this.childId = childId;
}
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Child child = new Child(100, 200);
oos.writeObject(child);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream("serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Child newChild = (Child) ois.readObject();
System.out.println(newChild.getParentId());
System.out.println(newChild.getChildId());
ois.close();
fis.close();
}
在父类属性没有实现Serializable接口时,子类序列化时,父类属性不会被序列化和反序列化,因此在输出结果中只能得到子类的属性值。
2.子类实现自己的readObject与writeObject:
public class Child extends Parent {
private static final long serialVersionUID = 1L;
private int childId;
public Child(int parentId, int childId) {
super(parentId);
this.childId = childId;
}
public int getChildId() {
return childId;
}
public void setChildId(int childId) {
this.childId = childId;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(getParentId());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
setParentId(in.readInt());
}
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Child child = new Child(100, 200);
oos.writeObject(child);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream("serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Child newChild = (Child) ois.readObject();
System.out.println(newChild.getParentId());
System.out.println(newChild.getChildId());
ois.close();
fis.close();
}
我们在Child类中添加了自己的writeObject和readObject方法,序列化时只需要序列化子类的属性,而在反序列化时,我们显式地从输入流中读取并设置父类的属性值,这样就能够正确地反序列化子类。
综上,了解继承序列化可以让我们更好地掌握Java的序列化机制,避免一些问题的出现。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:J2SE中的序列化之继承 - Python技术站