readObject() 与 readResolve() 恢复瞬态字段

发布于 2024-09-01 02:35:18 字数 699 浏览 3 评论 0原文

根据 Serialized javadoc,readResolve () 用于替换从流中读取的对象。但当然(?)您没有必须来替换该对象,所以可以使用它来恢复瞬态字段并返回原始引用,如下所示:

private Object readResolve() {
    transientField = something;
    return this;
}

与使用readObject相反()

private void readObject(ObjectInputStream s) {
    s.defaultReadObject();
    transientField = something;
}

当用于恢复瞬态字段时,是否有任何理由选择其中之一?实际上,我倾向于 readResolve() ,因为它不需要参数,因此在“正常”构造对象时也可以轻松使用它,在构造函数中,例如:

class MyObject {

    MyObject() {
        readResolve();
    }

    ...
}

According to Serializable javadoc, readResolve() is intended for replacing an object read from the stream. But surely (?) you don't have to replace the object, so is it OK to use it for restoring transient fields and return the original reference, like so:

private Object readResolve() {
    transientField = something;
    return this;
}

as opposed to using readObject():

private void readObject(ObjectInputStream s) {
    s.defaultReadObject();
    transientField = something;
}

Is there any reason to choose one over other, when used to just restore transient fields? Actually I'm leaning toward readResolve() because it needs no parameters and so it could be easily used also when constructing the objects "normally", in the constructor like:

class MyObject {

    MyObject() {
        readResolve();
    }

    ...
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2024-09-08 02:35:19

事实上,readResolve 的定义是为了让您更好地控制对象的反序列化方式。因此,您可以自由地做任何您想做的事情(包括为瞬态字段设置值)。

但是,我想您的瞬态字段设置为恒定值。在其他地方,这将是出现问题的明确信号:要么您的字段不是那么瞬态,要么您的数据模型依赖于错误的假设。

In fact, readResolve has been define to provide you higher control on the way objects are deserialized. As a consequence, you're left free to do whatever you want (including setting a value for an transient field).

However, I imagine your transient field is set with a constant value. Elsewhere, it would be the sure sign that something is wrong : either your field is not that transient, either your data model relies on false assumptions.

熟人话多 2024-09-08 02:35:19

使用readResolve。如果格式与预期的默认格式不同,则 readObject 方法允许您自定义对象的读取方式。这不是您想要做的。 readResolve方法,顾名思义,就是对读取到的对象进行解析,其目的正是让你解析反序列化后未恢复的对象状态。这就是你正在尝试做的事情。您可以从 readResolve 返回“this”。

Use readResolve. The readObject method lets you customize how the object is read, if the format is different than the expected default. This is not what you are trying to do. The readResolve method, as its name implies, is for resolving the object after it is read, and its purpose is precisely to let you resolve object state that is not restored after deserialization. This is what you are trying to do. You may return "this" from readResolve.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文