为什么这个类不可序列化?

发布于 2024-08-16 00:34:21 字数 530 浏览 8 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风筝有风,海豚有海 2024-08-23 00:34:22

使类 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 the MTRandom class stays binary compatible with java.util.Random, from which it is extended.

So theoretically, you could serialize an MTRandom instance, and deserialize it as a Random 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.

回心转意 2024-08-23 00:34:21

serialVersionUID的评论来看,作者似乎不想考虑序列化。添加瞬态可能会抑制某些编译器/IDE 警告。

From the comment on serialVersionUID, it looks like the author didn't want to consider serialisation. Adding transient may have suppressed some compiler/IDE warnings.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文