Core Java之序列化

original from : java.sun.com/developer/technicalArticles/Programming/serialization(Discover the secrets of the Java Serialization API)

Serialization is a built in mechnism in java, the serializable  works as a marker interface, which mean no other method need to be implement. 

But what if we have to do some extra work after unmashelling from a sequence of bytes  to live object? What if we want encrypt our bytes and decrypt it?

In order to achieve the goal, we better get more clear about the mechniams of serialization.

Why do we need serialization?
1.A object can exist as long as the JVM remain running.  Serialization provide us a way to keep the object into flatten file, we can restore it back to live object regardless of whether the object exist in the current memory managed by the JVM.
2. We need pass the object across the different JVMs. Object implement the serialzable is actually pass-by-value, it solve pass-by-reference in single jvm enviroment.

But how persist a object anyway?
The java.io.ObjectOutputStream class come to rescue, It's a default serialization protocol for us.(Node Streams can be used to write to file systems or even across sockets). That means we could easily transfer a flattened object across a network wire and have it be rebuilt on the other side. On the contrary,  ObjectInputStream is used to rebuilt the object.

Persist a Object

java 代码
  1. SomeObject some = new SomeObject();   
  2. String filename = "file.name";   
  3. FileOutputStream fos = null;   
  4. ObjectOutputStream out = null;   
  5. try{   
  6.     fos = new FileOutputStream(filename);   
  7.     out = new ObjectOutputStream(fos);   
  8.     out.writeObject(some);   
  9.     out.close();   
  10. catch(IOException ex) {   
  11.       ex.printStackTrace();   
  12. }   

Rebuild a Object

java 代码
  1. SomeObject some = null;   
  2. FileInputStream fis = null;   
  3. ObjectInputStream in = null;   
  4. try{   
  5.     fis = new FileInputStream(fileName);   
  6.     in = new ObjectInputStream(fis);   
  7.     some = (SomeObject)in.readObject();   
  8.     in.close();   
  9. catch(IOException ex) {   
  10.     ex.printStackTrace();   
  11. catch(ClassNotFoundException ex) {   
  12.     ex.printStackTrace();   
  13. }  

The class file must be accessible form the system in which the restoration occurs, In other words, the object's classes file and methods are not saved; only the object's state is saved.

Some object in java implement the serialzable, such as AWT and Swing GUI , strings ,and arrays.
But some , certain system-level classes such as Thread, OutputStream and its sublclasses ,and socket are not serializable.
It actually don't make any sence if they are serialized. Take Thread for example, Thread share the current heap in JVM, it done'st make any sence if the Thread rebuild at another JVM.

But How about our class has a Thread property, and every time the class initiated(in Constructor), the thread get started.
And we know that, when we rebuild a Object, it doesn't invoke the construtor, How could we add behavior after or before restoration?  

In order to solve this, we must find a way to customize the Default protocol.
This way can been work out by add a help method, and call the help method every time we finish our restoration.
Alternate way is use built-in  feature of the serializaiton methanism. developer can enhance the normal process by providing two methods inside their class file.

private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

The trick here is that the virtual machine will automatically check to see if either method is declared during the correspong method call.

out.defaultWriteObject()
in.defaultReadObject()
that's the normal process, we are only adding to it, and we can call some other method to do extra initialize the Object we want to rebuld.

Call to ObjectOutputStream.writeObject() kick off the serialization protoco. First the object is checked to ensure it implements Serializable and then it is checked to see whether either of those private methods are provided. If they are provided, the stream class is passed as the parameter, gtiving the code control over its usage.

If we don't want a Object which implement the Seriazable indirectly to be serialzable, we can throw NotSerializableExcetipn("don't serialize me") in both writeObject, readeObject method.

We could even create our own protocol by implementing the Externalizable interface. It deal with some non-java type persistent, provided you know how to read that specified type of file.

Gotchas(难倒你的意思)
Caching Objects in the stream
ObjectOutputStream out = new ObjectOutputStream();
MyObject obj = new MyObject();
obj.setState(100);
out.writeObject(obj);
obj.setState(200);
out.writeObject(obj);// does not save new object state

Solution: 1)close the stream after a write call;2)call reset()method.

Version control:

Keep our flatten object compatible with the Class even some field add to it after serilization occurs.
If you wish to control versioning, you have to provide the serialVersionUID field manually and ensure it is always the same.

The version control works great as long as the changes are compatible.

A complete  list of compatible and incompatible changes is given in the specification.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值