简体   繁体   English

在反序列化对象时如何找到对象所属的正确子类?

[英]How do I find the correct subclass an object belongs to while deserializing it?

This is the scenario. 这是方案。

I have a java code to write Serialized objects into a .ser file, and another to read the objects from the .ser file. 我有一个Java代码,可将序列化的对象写入.ser文件,而另一个代码可从.ser文件读取对象。

The code that does the Serialization also contains the class definition as follows- 执行序列化的代码还包含类定义,如下所示:

abstract class Currency implements Serializable{
    protected double value;
    abstract double getValue();
    abstract void print();
}

class Rupee extends Currency{
    Rupee(double val){
        value=val;
    }
    public double getValue(){
        return value;
    }
    public void print(){
        System.out.println("INR "+value);
    }
}

class Dollar extends Currency{
    Dollar(double val){
        value=val;
    }
    public double getValue(){
        return value;
    }
    public void print(){
        System.out.println("USD "+value);
    }
}

Now, I use a Currency reference that I can downcast to either Rupee or dollar, and I randomly generate Rupee and Dollar objects and serialize them into the .ser file. 现在,我使用货币参考,可以将其向下转换为卢比或美元,然后随机生成卢比和美元对象,并将它们序列化为.ser文件。

PROBLEM is, while deserializing this in another code, how do I distinguish the object being read between dollar or rupee object, as it could be either (randomly generated). 问题是,当在另一个代码中反序列化该对象时,如何区分正在读取的对象是美元对象还是卢比对象,因为它可能是随机生成的。 readObject() method only returns an Object type, and needs to be explicitly cast. readObject()方法仅返回Object类型,并且需要显式转换。 To cast, I first need to find out which class object it is. 要进行投射,我首先需要找出它是哪个类对象。 Help me out. 帮帮我。

You can use the operator instanceof to retrieve the type of the instance of a given object. 您可以使用运算符instanceof检索给定对象的实例的类型。

Example : if (currency instanceof Dollar) {...} 示例: if (currency instanceof Dollar) {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM