为什么Java有瞬态字段? [英] Why does Java have transient fields?
问题描述
为什么Java有瞬态字段?
Why does Java have transient fields?
推荐答案
瞬态Java中的
关键字用于表示字段不应该是序列化的一部分(这意味着保存,类似到文件中)。
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
字段:
变量可能标记为
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
,因此只有原始图像
序列化而不是保留原始图像和缩略图图像。这意味着保存序列化对象所需的存储空间更少。 (当然,根据系统的要求,这可能是也可能不合适 - 这只是一个例子。)
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.)
在反序列化时,< a href =http://java.sun.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject() =noreferrer> readObject $调用c $ c> 方法来执行将对象状态恢复到序列化发生状态所需的任何操作。这里需要生成缩略图,因此重写
readObject
方法,以便通过调用 generateThumbnail $ c $生成缩略图。 c>方法。
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 Serialization API的秘密文章(最初在Sun Developer Network上提供)有一节讨论了使用和提供 transient
关键字用于防止某些字段的序列化。
For additional information, the Discover the secrets of the Java Serialization API article (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屋!