反序列化的工作原理如何? [英] How Deserialization works?

查看:90
本文介绍了反序列化的工作原理如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,没有调用Object的序列化类的构造函数,而是第一个非序列化构造函数的no-arg构造函数。现在考虑以下代码

As far as my understanding goes constructor of class whose Object is serialized is not called but the no-arg constructor of 1st non serializable constructor. Now consider following code

public class SerializeDemo implements Serializable {

private String name;
int age;    //default 0

public SerializeDemo(String name, boolean setAge){
    this.name = name;
    if(setAge){
        this.age = 18;
    }
}

@Override
public String toString() {
    return "Name is " + name + " and age is " + age;
}

public static void main(String args[]) throws IOException, ClassNotFoundException {

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("//home//aniket//Desktop//serializedObjects.txt")));
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("//home//aniket//Desktop//serializedObjects.txt")));
    SerializeDemo sd = new SerializeDemo("Test",true);
    System.out.println("Before Serialization : " + sd);
    oos.writeObject(sd);
    SerializeDemo sdCopy = (SerializeDemo)ois.readObject();
    System.out.println("After Deserialization : " + sdCopy);
}
}

,输出为(按预期)

Before Serialization : Name is Test and age is 18
After Deserialization : Name is Test and age is 18

现在,具有no-arg构造函数的非序列化超类是Object(如果我错了,请纠正我)。所以基本上没有调用SerializeDemo构造函数。

Now the the non serializable super class having no-arg constructor is Object(Correct me if I am wrong). So basically SerializeDemo constructor is not called.

现在在反序列化期间创建Object时,它将尝试重建实例状态。所以它会把年龄设定为18岁。

Now when the Object is created during deserialization it will try to rebuild the instance state. So it will set age to 18.

问题是怎么回事?

我故意不提供年龄。也不是按照上面的讨论,它的构造函数被调用。那么它是如何设置的?(同样适用于名称)

I have deliberately not provided the setter. Nor as per above discussion it's constructor is called. So how is it set?(Same goes for name as well)

推荐答案

你可以看看 ObjectInputStream 源代码。它使用反射,它创建一个对象,从流中读取字段,并使用反射设置对象的字段。您可以在调试器中运行代码,然后一步一步地到达设置年龄的行。

You can take a look at ObjectInputStream source code. It uses reflection, it creates an object, reads fields from stream, and sets object's fields using reflection. You can run your code in a debugger and go step by step exactly to the line where age is set.

这篇关于反序列化的工作原理如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆