相关疑难解决方法(0)

Java对象序列化和继承

假设你有这两个类,Foo和Bar,其中Bar扩展了Foo并实现了它们 Serializable

class Foo {

public String name;

public Foo() {
    this.name = "Default";
}

public Foo(String name) {
    this.name = name;
}
}

class Bar extends Foo implements java.io.Serializable {

public int id;

public Bar(String name, int id) {
    super(name);
    this.id = id;
}
}
Run Code Online (Sandbox Code Playgroud)

请注意,Foo没有实现Serializable.那么当条形序列化时会发生什么?

    public static void main(String[] args) throws Exception {

    FileOutputStream fStream=new FileOutputStream("objects.dat");
    ObjectOutputStream oStream=new ObjectOutputStream(fStream);
    Bar bar=new Bar("myName",21);
    oStream.writeObject(bar);

    FileInputStream ifstream = new FileInputStream("objects.dat");
    ObjectInputStream istream = new ObjectInputStream(ifstream);
    Bar bar1 = …
Run Code Online (Sandbox Code Playgroud)

java inheritance serialization object-serialization

33
推荐指数
1
解决办法
2万
查看次数

反序列化ArrayList.没有有效的构造函数

这是我如何反序列化包含标识对象的arrayList

public 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我序列化它的方式

public void saveItemIdentification(ArrayList<Identification> identification,File file){
    try{
        ObjectOutputStream out = new ObjectOutputStream(
                                      new FileOutputStream(file));
        out.writeObject(identification);
    }catch(Exception e){
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我反序列化它时,它给了我这个错误

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 …
Run Code Online (Sandbox Code Playgroud)

java io serialization persistence deserialization

3
推荐指数
1
解决办法
4309
查看次数