Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - Why InvalidClassException is not thrown when I have deserialized in the parent class

Why I don't have an error while I am trying to read Child class into Parent's class variable? I thought that before asigning object that have been read compiler checks serialVersionUID of both classes (variable class and class that have been read) and if serialVersionUID is not equal InvalidClassException is thrown. So does A class and B class have the same serialVersionUID?

import java.io.*;

class A  {}

class B extends A implements Serializable {}

public class Test
{
    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        FileOutputStream fileOutputStream = new FileOutputStream("b.bin");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        B b1 = new B();
        objectOutputStream.writeObject(b1);
        objectOutputStream.close();
        
        FileInputStream fileInputStream = new FileInputStream("b.bin");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        A a1 = (A) objectInputStream.readObject(); // why I don't have an InvalidClass Exception here
        objectInputStream.close();
    }
}
question from:https://stackoverflow.com/questions/65644849/why-invalidclassexception-is-not-thrown-when-i-have-deserialized-in-the-parent-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, these two classes do not have the same serialVersionUID. There is no exception thrown because class B can be reconstructed successfully. There would for example be an InvalidClassException when the serialVersionUID would not match or when A would not implement a default constructor.

When you deserialise with objectInputStream.readObject(), an Object is returned which can be cast safely to B. Since B extends A, it can be upcasted to an object of type A – as it happens in your code.

On a sidenote, I strongly suggest that you define a serialVersionUID for your classes if you are directly storing and retrieving objects using serialisation.


You can get the serialVersionUID of the two classes as follows:

ObjectStreamClass.lookup(A.class).getSerialVersionUID()
ObjectStreamClass.lookup(B.class).getSerialVersionUID()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...