用readObject()反序列化一个类,并使用readObject返回的实例“替换”您从中调用的实例

通常,当反序列化一个类时,必须为其创建一个单独的实例:

try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(myFile));){
                TestClass tc = (TestClass)objectInputStream.readObject();
                myIndex = tc.getvalues();
            } catch (ClassnotFoundException e) {
                e.printStackTrace();
            }

我的问题是:如果您是从TestClass实例(this)调用此方法,可以代替创建单独的实例,而是将“ this”转换为readObject()返回的实例吗?如果没有,您是否可以以某种方式复制其字段而无需单独获取它们?

visionhansome 回答:用readObject()反序列化一个类,并使用readObject返回的实例“替换”您从中调用的实例

如何实现这种变化:

package clonetester;

import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;

class Deserialized
{
    Integer field;    
    static Replaceble getDeserialized() //throws CloneNotSupportedException
    {
        // Specify serialized object location to be read
        File myFile = new File("<parent>","<child>");
        try
        {
            ObjectInputStream objectInputStream =
                    new ObjectInputStream(new FileInputStream(myFile));
            return (Replaceble) objectInputStream.readObject()/*.clone()*/;
        }
        catch (IOException | ClassNotFoundException e)
        {
            return null;
        }
    }
}

class Replaceble extends Deserialized
{

    Replaceble that;
    Replaceble()
    {
        that = getDeserialized();
        if (that == null)
        {
            that = this;
        }        
    }

    // Instead of using this,use that
    // ...

    void save()
    {
        // Specify serialized object location to be written
        File myFile = new File("<parent>","<child>");
        try
        {
            ObjectOutputStream objectOutputStream =
                new ObjectOutputStream(new FileOutputStream(myFile));

            objectOutputStream.writeObject(that);

        }
        catch (IOException e) {}
    }

}

由于对象引用在Java中是不透明的,无需直接操作,因此在您的问题中分配给'this'的引用将需要指向您要还原的序列化对象的克隆,因此我无法弄清楚如何实现此对象仅通过使用Java重新定义分配给“ this”的引用。通过实现Cloneable接口,可以考虑从还原的序列化对象中进行某种重新分配的字段。

本文链接:https://www.f2er.com/2970387.html

大家都在问