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中的transient
关键字用于指示字段不应该是序列化(这意味着保存, 比如文件)过程的一部分。)
From the Java Language Specification, Java SE 7 Edition , Section 8.3.1.3.
(来自Java语言规范,Java SE 7 Edition , 第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.
(变量可以标记为transient
以指示它们不是对象的持久状态的一部分。)
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.
(例如,您可能具有从其他字段派生的字段,并且只应以编程方式执行,而不是通过序列化保持状态。)
Here's a GalleryImage
class which contains an image and a thumbnail derived from the image:
(这是一个GalleryImage
类,其中包含一个图像和从图像派生的缩略图:)
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();
}
}
In this example, the thumbnailImage
is a thumbnail image that is generated by invoking the generateThumbnail
method.
(在此示例中, thumbnailImage
是通过调用generateThumbnail
方法生成的缩略图图像。)
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.
(thumbnailImage
字段标记为transient
,因此仅序列化原始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.) ((当然,根据系统的要求,这可能是也可能不合适 - 这只是一个例子。))
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.
(在反序列化时,调用readObject
方法以执行将对象状态恢复到序列化发生状态所需的任何操作。)
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. (这里需要生成缩略图,因此会覆盖readObject
方法,以便通过调用generateThumbnail
方法生成缩略图。)
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序列化API的秘密”一文(最初在Sun Developer Network上提供),其中有一节讨论了如何使用transient
关键字来防止某些字段序列化的场景。)