欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Core Java之序列化 JavaJVMthreadSwingSocket 

程序员文章站 2022-07-12 11:11:50
...

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.