这是如何反序列化包含标识对象
的arrayListpublic void deserializeArrayList(){
String path = "./qbank/IdentificationHARD.quiz";
try{
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<Identification> list = (ArrayList<Identification>) in.readObject();
System.out.println(list);
}catch(Exception e){
e.printStackTrace();
}
}
这是我序列化的方式
public void saveItemIdentification(ArrayList<Identification> identification,File file){
try{
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(file));
out.writeObject(identification);
}catch(Exception e){
e.printStackTrace();
}
}
但是当我反序列化它时,它给了我这个错误
java.io.InvalidClassException: quizmaker.management.Identification; quizmaker.management.Identification; no valid constructor
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at quizmaker.management.Manage.deserializeArrayList(Manage.java:92)
这是第92行
ArrayList<Identification> list = (ArrayList<Identification>) in.readObject();
为什么会这样?
这是Identification
对象的代码。
package quizmaker.management;
import java.io.Serializable;
import quizmaker.Accounts.Rights.IAnswerable;
public class Identification extends Question implements Serializable{
private static final long serialVersionUID = 2L;
private String question;
private String answer;
public Identification(String q , String a){
super(q,a);
}
public String toString(){
return String.format("Question: %s\n Answer %s", getQuestion(),getAnswer());
}
}
答案 0 :(得分:10)
问题是 - &gt;在java中
Java serialization process only continues in object hierarchy till the class
is Serializable i.e. implements Serializable interface in Java.
在你的班级中,你正在调用super
类构造函数,它不是实现Serializable。
这就是问题.. :)
关于第二个问题,请查看JavaDoc
During deserialization, the fields of non-serializable classes will be
initialized using the public or protected no-arg constructor of the class.
A no-arg constructor must be accessible to the subclass that is serializable.
The fields of serializable subclasses will be restored from the stream.