为什么 Java 有瞬态字段? [英] Why does Java have transient fields?
问题描述
为什么 Java 有transient 字段?
Why does Java have transient fields?
推荐答案
Java 中的 transient
关键字用于指示字段不应作为序列化的一部分(意思是保存,例如一个文件)进程.
The transient
keyword in Java is used to indicate that a field should not be part of the serialization (which means saved, like to a file) process.
来自 Java 语言规范,Java SE 7 版, 第 8.3.1.3 节.transient
字段:
From the Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient
Fields:
变量可以标记为 transient
到表明他们不属于对象的持久状态.
Variables may be marked
transient
to indicate that they are not part of the persistent state of an object.
例如,您可能有从其他字段派生的字段,并且只能以编程方式完成,而不是通过序列化来持久化状态.
For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.
这是一个 GalleryImage
类,它包含一个图像和一个从图像派生的缩略图:
Here's a GalleryImage
class which contains an image and a thumbnail derived from the image:
class GalleryImage implements Serializable
{
private Image image;
private transient Image thumbnailImage;
private void generateThumbnail()
{
// Generate thumbnail.
}
private void readObject(ObjectInputStream inputStream)
throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
generateThumbnail();
}
}
在此示例中,thumbnailImage
是通过调用 generateThumbnail
方法生成的缩略图.
In this example, the thumbnailImage
is a thumbnail image that is generated by invoking the generateThumbnail
method.
thumbnailImage
字段被标记为transient
,所以只有原始image
被序列化而不是同时保留原始图像和缩略图.这意味着保存序列化对象所需的存储空间更少.(当然,根据系统的要求,这可能是也可能不是理想的——这只是一个例子.)
The thumbnailImage
field is marked as transient
, so only the original image
is serialized rather than persisting both the original image and the thumbnail image. This means that less storage would be needed to save the serialized object. (Of course, this may or may not be desirable depending on the requirements of the system -- this is just an example.)
反序列化时,readObject
方法被调用以执行将对象的状态恢复到序列化发生时的状态所需的任何操作.这里需要生成缩略图,所以重写了readObject
方法,以便通过调用generateThumbnail
方法来生成缩略图.
At the time of deserialization, the readObject
method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred. Here, the thumbnail needs to be generated, so the readObject
method is overridden so that the thumbnail will be generated by calling the generateThumbnail
method.
有关其他信息,请参阅文章 发现 Java 序列化 API 的秘密(最初在 Sun Developer Network 上提供)有一个部分讨论了使用 transient
关键字来防止某些字段的序列化的情况,并提供了一个场景.
For additional information, the article Discover the secrets of the Java Serialization API (which was originally available on the Sun Developer Network) has a section which discusses the use of and presents a scenario where the transient
keyword is used to prevent serialization of certain fields.
这篇关于为什么 Java 有瞬态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!