Java部分(de)对象序列化 [英] Java partial (de)serialization of objects

查看:126
本文介绍了Java部分(de)对象序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有3个类:

class foo { // not a singleton
    String s;
}
class bar {
    foo f;
    int i;
}
class baz {
    foo sameF;
}

现在我们创建实例

foo onlyFoo = new foo("the only one");
bar theBar = new bar(onlyFoo, 123);
baz theBaz = new baz(onlyFoo);

之后我们想将它们串行存储在一个文件中。
如果我们反序列化theBaz,修改onlyFoo并再次将theBaz反序列化到该文件,theBar仍包含原始的onlyFoo,因此有两个不同版本的onlyFoo。

After that we want to store them serilazed in a file. If we deserialze theBaz, modify onlyFoo and deserialize theBaz to the file again, theBar still contains the original onlyFoo, so there are two different versions of onlyFoo.

我想要的是我存储theBaz和theBar 没有 onlyFoo,分别存储三个对象,一旦有人反序列化theBaz我也想给他只有.Foo。如果他再次反序列化已更改的onlyFoo,则theBaz theBar将具有相同的仅修改的onlyFoo,因此如果有人请求一个对象(例如theBar),他将获得包含所有引用对象的完整序列化对象(onlyFoo)就像正常的序列化过程会返回一样。

What I want instead is that I store theBaz and theBar without onlyFoo, store the three objects separately and once someone deserialize theBaz I want to give him onlyFoo, too. If he deserializes the changed onlyFoo again, theBaz and theBar will have the same modified onlyFoo, so if someone requests an object (for example theBar) he gets the full serialized object with all the referenced objects (onlyFoo) like the normal serialization process would return.

我知道我必须存储对象并手动和单独保存引用,因为默认序列化无法处理这个问题。 我不知道的是如何部分序列化/反序列化Java对象?我需要将原语及其包装器与更高的对象分开并分别存储这些对象。

I know that I have to store the objects and keep the references manually and separately because the default serialization cannot handle this problem. What I don't know is how do I partially serialize/deserialize Java objects? I need to separate the primitives and their wrappers from the 'higher' objects and store this objects separately.

更新


  1. 我无法修改课程。

  2. 我不知道所有课程。它应该适用于我可能从未听说过的所有可序列化对象(它们可能是也可能不是最终的

  1. I cannot modify the classes.
  2. I don't know all classes. It should work with all serializable objects I maybe never heard about (they may or may not be final)


推荐答案

如果你想要更多的控制,你可以覆盖writeObject()和readObject()
并自己序列化。

If you want more controll you could overwrite writeObject() and readObject() and serialize yourself.

class bar {
    ...

    private void writeObject(ObjectOutputStream stream) throws IOException {
      // let version 1, later when you need to have versioning. 
      stream.writeInt(version);
      stream.writeInt(i);
      // leave out 
      // stream.writeObject(foo);

    }
}
// read object the analog, see 

http:// docs。 oracle.com/javase/6/docs/platform/serialization/spec/output.html#861

这篇关于Java部分(de)对象序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆