如何实现这种变化:
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