要初始化瞬态字段,最简单的解决方案是什么 [英] To initialize a transient field, what is the most simple solution

查看:206
本文介绍了要初始化瞬态字段,最简单的解决方案是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass implements Serializable {
  transient int myTransient;
  //Other variables
}

当我恢复这个课时我想要手动初始化 myTransient ,但我只想使用默认序列化。

When I restore this class I want to initialize myTransient manually, but otherwise I just want to use the default serialization.

如何注入 init()方法进入对象恢复过程而无需重写整个序列化机制,因为看起来像 Externalizable 会让我做?

How can I inject an init() method into the object restore process without re-writing the entire serialization mechanism as it seems like Externalizable would have me do?

推荐答案

实现 readObject()方法:

private void readObject(java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    myTransient = ...;
}

来自javadoc:

在序列化和反序列化过程中需要特殊处理的类必须使用这些确切的签名实现特殊方法:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void readObject(java。 io.ObjectInputStream in)
抛出IOException,ClassNotFoundException;

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

readObject方法负责从流中读取并恢复类字段。它可以调用in.defaultReadObject来调用恢复对象的非静态和非瞬态字段的默认机制。 defaultReadObject方法使用流中的信息来指定流中保存的对象的字段以及当前对象中相应命名的字段。这处理了类在演变为添加新字段时的情况。该方法不需要关注属于其超类或子类的状态。通过使用writeObject方法或使用DataOutput支持的原始数据类型的方法将各个字段写入ObjectOutputStream来保存状态。

The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

参见:

  • Serializable javadoc

这篇关于要初始化瞬态字段,最简单的解决方案是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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