Java 序列化,UID 未更改.我可以向类中添加新的变量和方法吗? [英] Java serialization, UID not changed. Can I add new variables and method to the class?

查看:10
本文介绍了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天全站免登陆