为什么这个类不可序列化?
我在 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVA/MTRandom.java 作为默认 < 的直接替代代码>java.util.Random类。然而,四个字段(一个 int、一个 boolean 和两个 byte[])被标记为 transient
。这意味着我无法在不实现自定义功能的情况下序列化此类的对象。
问题是,是否有任何原因将这些字段标记为瞬态?当从文件中读入对象时,是否有任何代码保存的信息没有任何意义?我从字段中删除了 transient
修饰符,它似乎工作正常,但我还没有对其进行深入测试,所以可能会出现它崩溃的情况吗?
就我个人而言,我不明白为什么,因为课堂上所做的都是算术。
I was using the Mersenne-Twister implementation at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVA/MTRandom.java as a drop-in replacement for the default java.util.Random
class. However, four fields (an int, a boolean and two byte[]) are marked as transient
. This means that I can't serialize an object of this class without implementing custom functionality.
The question is, is there any reason that these fields are marked transient? Is there any code in there that holds information that won't make any sense when the object is read in from a file? I removed the transient
modifier from the fields and it seems to work fine, but I haven't tested it intensively and so might there be cases where it breaks?
Personally, I can't see why, since all that's done in the class is arithmetic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使类
transient
的所有非静态字段的原因很可能是为了使MTRandom
类与保持二进制兼容>java.util.Random
,它是从它扩展而来的。因此理论上,您可以序列化一个 MTRandom 实例,并将其反序列化为一个 Random 实例,一切都会正常。
如果这些字段不是瞬态的,那么它们将被序列化并变得不兼容。
然而,据我所知,消除瞬变不会给您带来问题。
Most likely the reasoning behind making all of the non-static fields of the class
transient
was so that theMTRandom
class stays binary compatible withjava.util.Random
, from which it is extended.So theoretically, you could serialize an
MTRandom
instance, and deserialize it as aRandom
instance and everything would work.If those fields aren't
transient
, then they would be serialized and become incompatible.However, as far as I can tell, removing the transients shouldn't cause a problem for you.
从
serialVersionUID
的评论来看,作者似乎不想考虑序列化。添加瞬态可能会抑制某些编译器/IDE 警告。From the comment on
serialVersionUID
, it looks like the author didn't want to consider serialisation. Addingtransient
may have suppressed some compiler/IDE warnings.