如果我保存(序列化)一个对象,修改未序列化的对象然后反序列化该对象会发生什么。对象的反序列化版本是否会覆盖修改后的版本?或者我是否必须专门删除现有对象(或进行一些其他操作以确保正确的反序列化)?
PS 感谢您的回复。他们真的很有帮助。
答案 0 :(得分:0)
反序列化对象时,可以选择如何处理返回的反序列化Object引用。它不会影响您班级中的任何其他对象。
假设您有一个名为programObject的MyObjectType类型的对象。要序列化此对象,您可以执行以下操作:
ObjectOutputStream outputStream = new ObjectOutputStream(
new FileOutputStream("fileToWriteTo.dat");
这会将输出流设置为写入“fileToWriteTo.dat”。然后,要序列化此对象,您可以这样做:
outputStream.writeObject(programObject);
要将对象恢复到程序中,请创建一个输入流,如下所示:
ObjectInputStream inputStream = new ObjectInputStream(
new FileInputStream("fileToWriteTo.dat");
以下代码将从给定输入流反序列化对象并将其作为Object类型返回(因此转换为MyObjectType)。
programObject = (MyObjectType) inputStream.readObject();
这将有效地覆盖programObject。如果您不想这样做,只需将读入对象保存到新对象:
MyObjectType newObject = (MyObjectType) inputStream.readObject();
答案 1 :(得分:0)
序列化意味着将Object
的当前状态转换为其他形式。序列化版本与原始对象完全分开,因此对原始版本所做的更改不会影响序列化版本。
反序列化对象时,会得到一个 new 对象,其状态与序列化时的原始对象相同。
理解这一点的最好方法是举个例子。在这里,我们从列表[1, 2, 3]
开始,序列化列表,然后通过添加4
修改原始列表。当我们反序列化原始文件时,我们得到一个仅包含[1, 2, 3]
的新列表。为简单起见,我已将对象保存为字节数组,但我可以轻松将其保存到文件中。
public static void main(String[] args) throws Exception {
// Create a list
List<Integer> original = new ArrayList<>(Arrays.asList(1, 2, 3));
// Serialize the list as a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(original);
byte[] serializedList = baos.toByteArray();
// Modify the list
original.add(4);
// Deserialize the original
Object newList = new ObjectInputStream(new ByteArrayInputStream(serializedList)).readObject();
// Print the 2 versions
System.out.println(original); // [1, 2, 3, 4]
System.out.println(newList); // [1, 2, 3]
}