问题描述
public class Foo implements java.io.Serializable {
private int v1;
private static double v2;
private Loan v3 = new Loan();
}
选项:
A. Foo的一个实例可以被序列化,因为Foo实现了Serializable。
B. Foo的一个实例无法序列化,因为Foo包含一个不可序列化的实例变量v3。
C.如果你将v3标记为瞬态, Foo的一个实例是可序列化的。
D. b和c
Options:
A. An instance of Foo can be serialized because Foo implements Serializable.
B. An instance of Foo cannot be serialized because Foo contains a non-serializable instance variable v3.
C. If you mark v3 as transient, an instance of Foo is serializable.
D. b and c
答案:D
说明:即使对象实现 java.io.Serializable
,也可能无法序列化对象,因为它可能包含不可序列化的实例变量。
Explanation: An object may not be serialized even though its class implements java.io.Serializable
, because it may contain non-serializable instance variables.
现在我的问题是:
据我所知,transient是关闭序列化。那么在这种情况下如何瞬态,帮助我们序列化foo?
As far as I know, transient is used to turn off serialization. Then how is transient in this case, helping us to serialize foo?
推荐答案
transient
不会完全禁用序列化;它只是标记了不会被序列化的成员。它通常用于在对象被反序列化时不正确或不相关的东西,或者存储不太安全的东西(密码,解密数据,那种东西),或者不可序列化的东西很容易重建。
transient
doesn't disable serialization altogether; it just marks members that won't be serialized. It's typically used for stuff that would be incorrect or irrelevant when the object is unserialized, or stuff that it'd be less-than-safe to store (passwords, decrypted data, that sort of thing), or non-serializable stuff that could be easily reconstructed.
在这种情况下,我假设贷款
类不可序列化。 (如果是,那么A就是正确的。)标记 v3
因为瞬态只是告诉Java不要担心该字段,而是继续并序列化其他字段。这意味着未序列化的 Foo
可能具有null v3
。如果您还要存储贷款
,则需要跟踪足够的信息以便随意重新创建,或更改类贷款
以便它实现 java.io.Serializable
。
In this case, i assume the Loan
class isn't serializable. (If it were, then A would be correct.) Marking v3
as transient just tells Java not to worry about that field, but go ahead and serialize the others. This means an unserialized Foo
might have a null v3
. If you want to store the Loan
as well, you'd need to either keep track of enough info to recreate it at will, or change class Loan
so that it implements java.io.Serializable
as well.
或者,那里如果需要控制序列化,可以实现的方法( writeObject
, readObject
)。但这可能有点麻烦。
Alternatively, there are methods you could implement (writeObject
, readObject
) if you need control over serialization. But that can be a bit of a hassle.
这篇关于如何将字段标记为瞬态可以序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!