首页 / JAVA / 带继承的序列化(Java)
带继承的序列化(Java)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了带继承的序列化(Java),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2571字,纯文字阅读大概需要4分钟。
内容图文
![带继承的序列化(Java)](/upload/InfoBanner/zyjiaocheng/686/ddd856d4170b4fc0974bec3a2b0b4be6.jpg)
我正在学习序列化和继承,并且我不了解谁在反序列化过程中调用了no-arg构造函数.超类A不实现Serializable,而子类B扩展A实现Serializable.
超类A
public class A {
int i;
public A(int i)
{
this.i = i;
}
public A()
{
i = 50;
System.out.println("A's class constructor called");
}
}
B类
import java.io.Serializable;
public class B extends A implements Serializable {
int j;
// parameterized constructor
public B(int i,int j)
{
super(i);
this.j = j;
}
}
驾驶员等级
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args) throws Exception {
B b1 = new B(10,20);
System.out.println("i = " + b1.i);
System.out.println("j = " + b1.j);
// Serializing B's(subclass) object
//Saving of object in a file
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
// Method for serialization of B's class object
oos.writeObject(b1);
// closing streams
oos.close();
fos.close();
System.out.println("Object has been serialized");
// De-Serializing B's(subclass) object
// Reading the object from a file
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
// Method for de-serialization of B's class object
B b2 = (B)ois.readObject(); // The A() constructor is called here
// closing streams
ois.close();
fis.close();
System.out.println("Object has been deserialized");
System.out.println("i = " + b2.i);
System.out.println("j = " + b2.j);
}
}
如果删除A()构造函数,则会收到InvalidClassException.我看到在创建b2对象时调用了A(),但我不明白为什么在此语句中调用此A()以及调用它的人.
创建b1对象时,将调用B(int i,int j)构造函数以及A(int i)构造函数.这很容易理解.但是我不明白为什么在创建b2对象时调用A()构造函数.
解决方法:
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.
现在您的问题:
If I delete the A() constructor I get the InvalidClassException. I see that A() is called when the b2 object is created but I don’t understand why this A() is called at this statement and who called it.
串行化机制通过反射调用A()构造函数.特别是通过ObjectStreamClass从ObjectInputStream获得.
内容总结
以上是互联网集市为您收集整理的带继承的序列化(Java)全部内容,希望文章能够帮你解决带继承的序列化(Java)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。