通常,当您反序列化一个类时,您必须为其创建一个单独的实例:
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(myFile));){
TestClass tc = (TestClass)objectInputStream.readObject();
myIndex = tc.getValues();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
我的问题是:如果您从 TestClass 实例(this)调用 this,您是否可以不创建单独的实例,而将“this”转换为 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 接口(interface),可以考虑从恢复的序列化对象中重新分配字段。
关于java - 使用 readObject() 反序列化一个类,并将 "subsititute"调用它的实例与 readObject 返回的实例一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59194950/