serializable 类型的 id 有什么好处?

java8004 2011-08-23 10:40:35
为什么我见有的id是这个类型的。。。有什么特点或作用?
...全文
1788 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
teemai 2011-08-28
  • 打赏
  • 举报
回复
主要是让你这个对象有唯一的标识!就是说序列化和反序列话后要保持版本一致!

可以看我博客有详细的说明:

http://blog.csdn.net/huxiweng/article/details/6715770
淡定的峰哥 2011-08-28
  • 打赏
  • 举报
回复
对象序列化是为了反序列化用的
比如将一个对象写入到文件,或者作为流的形式传给第三方,那么这个类必须实现Serializable接口,并且定义一个私有的常量SerializableID,不然就不能从文件中读取对象了,接收方也没法还原这个对象
飓风zj 2011-08-28
  • 打赏
  • 举报
回复
记录序列化后的版本号。。仅此而已吧
龙四 2011-08-28
  • 打赏
  • 举报
回复
不是说特定或好处,是有作用的

比如你定义了一个Student类,里面定义了一个SerializableID=5,序列化后传给我,我将其存到数据库以后再使用

若干天后,系统升级,你在Student类加了一个字段String address,如果Student里没有定义SerializableID或者SerializableID不一样了,我存在数据库里的Student对象就反序列化不回来了

如果定义了SerializableID,即使你在Student里加了一个属性,我存在数据库的对象少一个属性,但还是可以反序列化回来的,只是新加的那个属性值为null而已


[Quote=引用 3 楼 java8004 的回复:]

还是不太懂。。
private Serializable id;
这有什么特点或好处。。
[/Quote]
java8004 2011-08-28
  • 打赏
  • 举报
回复
还是不太懂。。
private Serializable id;
这有什么特点或好处。。
HeiBoyYang 2011-08-23
  • 打赏
  • 举报
回复
int:Integer
long:Long
jdk1.5自动装箱,int会自转换为Integer,而Integer是实现了Serializable的,所以可以。
jdk1.4不自动装箱拆箱,所以要手动构造new Integer(int) new Long(long)



/**
* Constructs a newly allocated <code>Integer</code> object that
* represents the <code>int</code> value indicated by the
* <code>String</code> parameter. The string is converted to an
* <code>int</code> value in exactly the manner used by the
* <code>parseInt</code> method for radix 10.
*
* @param s the <code>String</code> to be converted to an
* <code>Integer</code>.
* @exception NumberFormatException if the <code>String</code> does not
* contain a parsable integer.
* @see java.lang.Integer#parseInt(java.lang.String, int)
*/
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
鱼鱼 2011-08-23
  • 打赏
  • 举报
回复
你说的是serialVersionUID吧,这个是为了在序列化时区分类的版本
你看一下Serializable的Doc
其中说道
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧