序列化中的java.io.InvalidClassException

时间:2013-04-17 17:43:05

标签: java exception serialization

阅读序列化后,我尝试对书中提供的示例进行实验。以下代码有一些变化,这基本上是从SCJP书中选取的。

import java.io.FileInputStream;

public class SerializationTest {
    public static void main(String[] args) {
        Collar c = new Collar(4);
        Dog d = new Dog(c, "Sheru", 32);
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(
                    "C:\\Users\\dell\\Desktop\\NewDir\\DogState.txt");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(d);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // ***************************************************************************************************
        // //
        Dog restore = null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(
                    "C:\\Users\\dell\\Desktop\\NewDir\\DogState.txt");
            ois = new ObjectInputStream(fis);
            restore = (Dog) ois.readObject();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("after: dog name: "+ restore.name +" , collar=" + restore.getCollar());
        System.out.println("Animal material is:" + restore.getWeight());
    }
}

// Intentionally added parameterized constructor so that default constructor is not called.
class Animal{
    int weight = 42;
    public Animal(int weight) {
        this.weight = weight;
        System.out.println("animal constructor");
    }
}


class Dog extends Animal implements Serializable {
    String name;
    transient Collar collar;

    public Collar getCollar() {
        return collar;
    }

    public void setCollar(Collar collar) {
        this.collar = collar;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public Dog(Collar collar, String name, int weight) {
        super(weight);
        System.out.println("Dog constructor");
        this.collar = collar;
        this.name = name;
    }

}
class Collar {
    int size;

    public Collar(int size) {
        System.out.println("Collar constructor");
        this.size = size;
    }
}

这里我的问题是为什么会发生InvalidClassException,请解释异常的根本原因。 当前输出是

Collar constructor
animal constructor
Dog constructor
java.io.InvalidClassException: Dog; Dog; 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 SerializationTest.main(SerializationTest.java:39)
Caused by: java.io.InvalidClassException: Dog; no valid constructor
    at java.io.ObjectStreamClass.<init>(Unknown Source)
    at java.io.ObjectStreamClass.lookup(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at SerializationTest.main(SerializationTest.java:18)
Exception in thread "main" java.lang.NullPointerException
    at SerializationTest.main(SerializationTest.java:54)

如果我删除Animal构造函数并注释掉Dog构造函数中的super(weight),则输出为

Collar constructor
Dog constructor
after: dog name: Sheru , collar=null
Animal material is:42

我理解这个输出,并且我还得到这样的事实:在反序列化期间调用了serialzable类的超类构造函数但是这里没有默认构造函数,所以发生了异常。但是为什么我想知道这个例外。

3 个答案:

答案 0 :(得分:1)

尝试从文件中读取时会抛出异常:

at java.io.ObjectInputStream.readObject(Unknown Source)
at SerializationTest.main(SerializationTest.java:39)

堆栈跟踪清楚地表明程序在尝试读取对象时中止。令你困惑的是引用写入的第二个堆栈跟踪:

at java.io.ObjectOutputStream.writeObject(Unknown Source)
at SerializationTest.main(SerializationTest.java:18)

但您似乎已跳过此非常重要的一行:

Caused by: java.io.InvalidClassException: Dog; no valid constructor

Java堆栈跟踪可以嵌套,一个例外可以导致另一个;这是一个小小的尴尬。事实上,在对象的序列化过程中,已经计算出没有默认构造函数。以下是involved source code的摘录:

...
cons = getSerializableConstructor(cl);
...
} else if (cons == null) {
    deserializeEx = new InvalidClassException(name, "no valid constructor");
}

这意味着在写入期间,已经很清楚没有有效的构造函数。但是,异常不会被抛出,而是与对象一起序列化。稍后,在反序列化时,会调用此代码:

void checkDeserialize() throws InvalidClassException {
    if (deserializeEx != null) {
        InvalidClassException ice =
            new InvalidClassException(deserializeEx.classname,
                                      deserializeEx.getMessage());
        ice.initCause(deserializeEx);
        throw ice;
    }
}

这里抛出了“真正的”异常,但是它的原因被设置为在对象序列化期间存储的异常。

这种机制只能在SUN / Oracle的Java实现中找到; OpenJDK在尝试读取时会明显抛出异常,并且不会在写入时保留堆栈跟踪。

答案 1 :(得分:0)

非Serializable基类Dog必须具有可访问的默认构造函数。当您注释掉Dog(weight)构造函数时,会强制编译器提供一个,当您将它保留在编译器中时,不会提供一个。

答案 2 :(得分:0)

有一条规则,即序列化类的父类或与该的任何任何关联类必须实现Serializable
以您为例,当您删除super(weight);时,它将检查默认构造函数并正常运行
。但是,如果您放置class Animal implements Serializable,则代码也将正常运行。