Java序列化,UID没有改变。我可以在课程中添加新的变量和方法吗? [英] Java serialization, UID not changed. Can I add new variables and method to the class?

查看:117
本文介绍了Java序列化,UID没有改变。我可以在课程中添加新的变量和方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序列化的类。现在我需要使用setter和getter方法在类中添加一个新变量。这个类在RMI中通过线路发送。

I have a class that is serialised. Now I need to add a new variable into the class, with setter and getter methods. This class is sent over wire in RMI.

在不更改UID的情况下,我可以为它添加新参数和getter和setter方法吗?我尝试编写一个通过线程发送的示例类,并没有更改UID,并为其添加了新参数和getter以及setter方法。另一方面,我测试了它,我仍然得到了正确的值。我曾假设,如果我添加新参数,getter和setter方法,我需要更改UID。我错了吗?

Without changing the UID, can I add new parameters and getter and setter methods for it? I tried to write an example class that is sent over wire, and did not change the UID, and added new parameters and getter and setter methods for it. On the other end, I tested it and I still got the values properly. I had assumed, if I add new parameters, getter and setter methods, I need to change the UID. Am I wrong?

推荐答案

如果您对类的SerialVersionUID进行硬编码(通常为1L),请存储一些实例,然后重新定义类,你基本上得到这种行为(这或多或少常识):

If you hard-code the SerialVersionUID of a class, (to 1L, usually), store some instances, and then re-define the class, you basically get this behavior (which is more or less common sense):


  1. 新字段(目前)在类定义中,不存在于序列化实例中)被赋予一个默认值,对于对象为null,或者与基元的未初始化字段具有相同的值。

  2. 删除的字段(不存在)在类定义中,但在序列化实例中存在)只是被忽略。

所以一般的经验法则是,如果你只是添加字段和方法,并且不要更改任何现有的东西,如果你对这些新字段的默认值没问题,你通常都可以。

So the general rule of thumb is, if you simply add fields and methods, and don't change any of the existing stuff, AND if you're OK with default values for these new fields, you're generally OK.

这篇关于Java序列化,UID没有改变。我可以在课程中添加新的变量和方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆