java - 通过 ObjectInputStream 和 transient 字段序列化

标签 java serialization transient objectinputstream

这个问题是关于 ObjectInputStream 以及它如何构建声明为 transient 的字段。考虑 ObjectInputStream 的一个简单用例

FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
SomeClass sc = (SomeClass) ois.readObject();

SomeClass 在哪里

class SomeClass {
   int x;
   transient OtherClass y;
}

class OtherClass {
   int z;
}

在 ois.readObject 之后 sc.y 的值是多少?

我想澄清一下我在 docs.oracle.com 上读到的内容哪个州

“声明为 transient 或静态的字段会被反序列化过程忽略。对其他对象的引用会导致在必要时从流中读取这些对象。”

transient 字段被忽略是什么意思?如果它们是 transient 的(即未序列化——我是怎么理解的……),如何从流中读取它们?

马蒂亚斯

最佳答案

what will be the value of sc.y after ois.readObject ?

Someclass.y 将是“默认值”。在这种情况下,因为它是一个对象,所以它将是 null

What does it mean that transient fields are ignored?

它们没有序列化——它们被跳过了。来自Java Object Serialisation Specification :

A Serializable class must do the following:

  • Implement the java.io.Serializable interface
  • Identify the fields that should be serializable (Use the serialPersistentFields member to explicitly declare them serializable or use the transient keyword to denote nonserializable fields.)

...和...

The easiest technique is to mark fields that contain sensitive data as private transient. Transient fields are not persistent and will not be saved by any persistence mechanism. Marking the field will prevent the state from appearing in the stream and from being restored during deserialization. Since writing and reading (of private fields) cannot be superseded outside of the class, the transient fields of the class are safe.

你的下一个问题:

And how can they be read from the stream if they are transient

它们不在流中 - 所以,实际上,它们没有被读取。如上所述,最终作为该类型的“默认值”(对象为 null,基元为 0/false)。

"Fields declared as transient or static are ignored by the deserialization process."

对于最常见的情况,它们会被序列化 过程忽略 - 因此,它们不在流中,也不会被反序列化。但是,如果您在序列化对象之后更改了类,以便以前序列化的字段现在标记为 transient ,那么反序列化过程将在流中找到该值时忽略该值。

关于java - 通过 ObjectInputStream 和 transient 字段序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531076/

相关文章:

grails - Grails 域中的 transient 属性

java - 如何从 Java 反序列化概念中声明为 transient 的文件中检索成员?

java - Java中的静态变量未初始化

java - 如何在使用 JSch SFTP 库时解析 Java UnknownHostKey?

javascript - 如何删除jquery id中的前缀

java - Spark Scala 中的任务不可序列化错误

java - 处理序列化类中包含 transient 成员的线程的正确做法

java - 替换条件 If 语句

java - 给定范围内复杂度较低的素数

java - 序列化是否适用于未定义为可序列化的其他对象实例?