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 代码
- SomeObject some = new SomeObject();
- String filename = "file.name";
- FileOutputStream fos = null;
- ObjectOutputStream out = null;
- try{
- fos = new FileOutputStream(filename);
- out = new ObjectOutputStream(fos);
- out.writeObject(some);
- out.close();
- } catch(IOException ex) {
- ex.printStackTrace();
- }
Rebuild a Object
java 代码
- SomeObject some = null;
- FileInputStream fis = null;
- ObjectInputStream in = null;
- try{
- fis = new FileInputStream(fileName);
- in = new ObjectInputStream(fis);
- some = (SomeObject)in.readObject();
- in.close();
- } catch(IOException ex) {
- ex.printStackTrace();
- } catch(ClassNotFoundException ex) {
- ex.printStackTrace();
- }
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.
分享到:
- 2007-09-08 20:45
- 浏览 1885
- 评论(0)
- 论坛回复 / 浏览 (0 / 2238)
- 查看更多
相关推荐
Xson是一个Java对象序列化和反序列化程序。支持Java对象到字节数组的序列化,和从字节数组到Java对象的反序列化。 Maven: <groupId>com.github.xsonorg</groupId> <artifactId>xson-core <version>1.0.1 ...
Jackson是Java领域中广泛使用的JSON处理库,它提供了高效的JSON序列化和反序列化功能。在Java应用程序中,我们经常需要将Java对象转换为JSON字符串(序列化)或从JSON字符串恢复Java对象(反序列化),Jackson库就是...
“core”可能是指核心源代码文件或库,包含实际的protobuf压缩和序列化逻辑。 综上所述,这个压缩包提供了一种自定义实现的protobuf压缩解决方案,包括了protobuf的序列化和反序列化功能,以及可能的压缩算法实现。...
Jackson是Java领域中广泛使用的JSON处理库,它提供了高效的序列化和反序列化功能,能够将Java对象转换为JSON格式的字符串,同时也能将JSON数据转换回Java对象。在这个小例子中,我们将深入探讨如何使用Jackson进行...
jackson-databind-2.16.1.jar java json 序列化包
JSON序列化和反序列化是现代Web开发中不可或缺的技术之一。在C#中,可以根据具体需求选择不同的序列化工具。对于.NET Framework项目,DataContractJsonSerializer和JavaScriptSerializer都是不错的选择;而对于.NET ...
8. **模块化**: protostuff-master这个压缩包很可能包含了多个模块,每个模块专注于特定的功能,如protostuff-core用于核心序列化,protostuff-runtime用于运行时序列化,可能还有针对不同数据格式的模块如...
XML序列化就是将Java对象转换为XML格式的字符串,以便于存储或者在网络上传输。反之,反序列化则是将XML数据转换回Java对象。这个过程可以帮助我们方便地保存和恢复应用程序的状态,或者与服务器进行数据交互。 在...
在本文中,我们将深入探讨Bboss和Xstream两个序列化和反序列化库在性能方面的差异。这两个库在Java开发中广泛用于将对象转换为XML格式,以便于存储、传输或持久化。以下是对这两个库的详细分析。 首先,Bboss和...
- **对象序列化**:了解如何将对象转换为字节流,以便存储或网络传输。 4. **多线程**: - **线程的创建**:通过Thread类或实现Runnable接口创建线程。 - **同步机制**:synchronized关键字、wait()、notify()和...
5. **输入/输出(I/O)**:涵盖流的概念,文件读写,以及数据的序列化。 6. **基本的GUI编程**:使用Java Swing库创建图形用户界面,包括JFrame、JButton、JLabel等组件的使用。 卷2,通常称为"Advanced Features",...
- 文件输入输出流FileInputStream/FileOutputStream,对象序列化与反序列化。 - 文件读写高级操作:Scanner、PrintWriter、FileReader/FileWriter。 5. **多线程** - 线程的创建:通过Thread类和实现Runnable...
Java 的 MessagePack 序列化器实现 / msgpack.org[Java]用于 Java 的 MessagePackMessagePack是一种二进制序列化格式。如果您需要一种快速而紧凑的 JSON 替代方案,MessagePack 就是您的好帮手。例如,小整数可以用...
总结来说,`serialVersionUID`是Java序列化机制的一个关键部分,它帮助维护序列化对象的版本一致性。理解并正确使用`serialVersionUID`对于编写可序列化类和处理跨版本数据交换至关重要。在实际开发中,我们应该养成...
12. **输入/输出流**:掌握I/O流的基本概念,学习文件读写,以及对象序列化与反序列化。 13. **多线程**:理解并发编程的基础,包括线程的创建方式(实现Runnable接口或继承Thread类),同步机制(synchronized...
是二进制序列化格式。 如果您需要快速,紧凑的JSON替代方案,那么MessagePack是您的朋友。 例如,可以将一个小整数编码为一个字节,而短字符串则只需要一个字节前缀+原始字节数组即可。 MessagePack实现已经有多种...
5. **输入/输出系统**:涵盖了File类,NIO(New I/O)框架,以及数据的序列化和反序列化。 6. **多线程**:讲解了如何在Java中实现并发编程,包括线程的创建、同步机制(如synchronized关键字和Lock接口)。 7. **...
5. **输入/输出流**:涵盖文件操作、数据流、序列化和对象的持久化。 6. **字符串和正则表达式**:讨论String类的特点和常用方法,以及正则表达式的使用。 卷二则更倾向于高级主题,包含: 1. **多线程编程**:讲解...
5. 序列化:Java的序列化机制允许对象的状态被持久化。书中会介绍如何实现`Serializable`接口,序列化和反序列化的操作,以及优化序列化性能的策略。 6. 类加载器:Java的类加载机制是其动态性的重要组成部分。这...