[Java learning notes] serialization and deserialization of Objects

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

1. Definition:

Serialization is also called serialization-writing an object to an output stream (usually a file. Deserialization reads an object from an input stream. The members in the class must be serializable and must implement the serializable interface so that the class objects can be serialized and deserialized. This interface is a representative interface.SerialversionuidIt is a universal identifier of a serializable class. This identifier is used to ensure that a loaded class corresponds to a serializable object.

If you specify the serialversionuid, you can add a field or method after serialization without affecting subsequent restoration. The restored object can still be used, you can also use more methods. The generation of serialversionuid can be 1 or 2, but it is best to generate a unique fingerprint number according to the digest algorithm. eclipse can generate it automatically, and JDK also comes with this tool. The general syntax is similar
Private Static final long serialversionuid =-763618247875550322l;

 

For simple use, please take part in another of my exercises: http://blog.csdn.net/gnuhpc/archive/2009/08/01/4396149.aspx

 

2. serialization steps:

1) create an object output stream: You can wrap an output stream of another type.

2) write an object through the writeobject () of the object output stream. Use type conversion to convert to the object of the corresponding class.

3. deserialization steps:

1) create an object input stream: You can wrap an output stream of another type.

2) write an object through the readobject () of the object output stream.

4. What objects need to be serialized?

The basic idea of serialization is to guarantee the instance information. Because the instance information disappears after running. What information should I store? It must not be information about methods.

 

5. precautions:

A. if you want to further control serialization and deserialization, the class provides readobject () method and writeobject () method. The custom method is called during deserialization. Note that these two methods are not defined in the Java. Io. serializable interface, but in the objectinputstream and objectoutputstream classes. These two classes implement the objectinput and objectoutput interfaces. The following is an example of a variable array, taken from Java in a nutshell 2rd edition. It achieves efficient methods to adjust the degree of variable arrays in serialization:

public class IntList implements Serializable{  private int[] nums = new int[8]; // An array to store the numbers.  private transient int size = 0;  // Index of next unused element of nums[].  /** Return an element of the array */  public int elementAt(int index) throws ArrayIndexOutOfBoundsException {    if (index >= size) throw new ArrayIndexOutOfBoundsException(index);    else return nums[index];  }  /** Add an int to the array, growing the array if necessary. */  public void add(int x) {    if (nums.length == size) resize(nums.length*2); // Grow array, if needed.    nums[size++] = x;                               // Store the int in it.  }  /** An internal method to change the allocated size of the array. */  protected void resize(int newsize) {    int[] oldnums = nums;    nums = new int[newsize];                     // Create a new array.    System.arraycopy(oldnums, 0, nums, 0, size); // Copy array elements.  }  /** Get rid of unused array elements before serializing the array. */  private void writeObject(ObjectOutputStream out) throws IOException {    if (nums.length > size) resize(size);  // Compact the array.    out.defaultWriteObject();              // Then write it out normally.  }  /** Compute the transient size field after deserializing the array. */  private void readObject(ObjectInputStream in)          throws IOException, ClassNotFoundException {    in.defaultReadObject();                // Read the array normally.    size = nums.length;                    // Restore the transient field.  }}

B. Because serialization is for class instances, that is, objects, members such as static are class-related and will not be serialized.

C. Note that once a class in an API is serialized, its parent class is serialized. If you want to serialize your own classes, ensure that their parent classes are serialized. Once the parent class is serialized, the Child classes are automatically serialized. Therefore, serialization is not recommended for internal and extensible classes.

D. to Encrypt serialized data, you can rewrite writeobject and readobject, write the encryption algorithm into it, and finally call stream. defaultwriteobject (); or stream. defaultreadobject (); Implement obfuscation -- if you want to perform any operations before and after serialization and deserialization, you can customize them here. For example, the parent class of this class implements serialization, but you don't want this class to be serialized, so you can throw an exception when serializing or deserializing:

 

private void writeObject(ObjectOutputStream out) throws IOException{     throw new NotSerializableException("Not today!");}private void readObject(ObjectInputStream in) throws IOException{     throw new NotSerializableException("Not today!");}

 

To encrypt and sign the entire object, put it in a javax. crypto. sealedobject and/or Java. Security. signedobject package. Both are serializable, so you can create a "Packing Box" around the original object by packaging the object in sealedobject ". A symmetric key is required for decryption, and the key must be managed separately. Likewise, signedobject can be used for data verification, and the symmetric key must be managed separately.

E. serialization is not a file or method of the target object, but the object state. Therefore, the class file of the object must exist during deserialization.

F. If you want to create your own serializable method, implement the externalizable interface instead of the serializable interface. Rewrite the following two methods:

 

Public void writeexternal (objectoutput out) throws ioexception;

Public void readexternal (objectinput in) throws ioexception, classnotfoundexception;

Note that you can do everything without the default action. In addition, this interface is no different from the serialized interface. The default serialization method may incur time overhead. If you want to optimize the method, you can start with customizing a simple serialization method. The actual purpose of this interface is that if you want to serialize the data members of the parent class, the original serialized interface cannot meet the requirements. You must customize the serialization method:

[Java: nogutter]View plaincopyprint?

  1. Import java. Io .*;
  2. Public class testexternalizable
  3. {
  4. Fileoutputstream fout = NULL;
  5. Objectoutputstream objout = NULL;
  6. Public testexternalizable (){
  7. Try {
  8. Testsub = new testsub ();
  9. Testsub. setname (name );
  10. Testsub. setage (AGE );
  11. Fout = new fileoutputstream (file_name );
  12. Objout = new objectoutputstream (fout );
  13. Objout. writeobject (testsub );
  14. Objout. Flush ();
  15. Objout. Close ();
  16. Fout. Close ();
  17. Fileinputstream fin = new fileinputstream (file_name );
  18. Objectinputstream objin = new objectinputstream (FIN );
  19. Testsub Ts = (testsub) objin. readobject ();
  20. Objin. Close ();
  21. Fin. Close ();
  22. System. Out. println (TS. Name + "" + ts. Age );
  23. } Catch (exception ex ){
  24. Ex. printstacktrace ();
  25. }
  26. }
  27. Public static void main (string [] ARGs)
  28. {
  29. New testexternalizable ();
  30. }
  31. }
  32. Class testsuper {
  33. String name = NULL;
  34. Int age = 0;
  35. Public void setname (string name ){
  36. This. Name = Name;
  37. }
  38. Public void setage (INT age ){
  39. This. Age = age;
  40. }
  41. Public void readexternal (objectinput ){
  42. Try {
  43. Name = (string) objectinput. readobject ();
  44. Age = objectinput. readint ();
  45. } Catch (exception ex ){
  46. Ex. printstacktrace ();
  47. }
  48. }
  49. Public void writeexternal (objectoutput ){
  50. Try
  51. {
  52. Objectoutput. writeobject (name );
  53. Objectoutput. writeint (AGE );
  54. } Catch (exception ex ){
  55. Ex. printstacktrace ();
  56. }
  57. }
  58. }
  59. Class testsub extends testsuper implements externalizable {
  60. Public testsub (){
  61. }
  62. }

Import Java. io. *; public class testexternalizable {fileoutputstream fout = NULL; objectoutputstream objout = NULL; Public testexternalizable () {try {testsub = new testsub (); testsub. setname (name); testsub. setage (AGE); fout = new fileoutputstream (file_name); objout = new objectoutputstream (fout); objout. writeobject (testsub); objout. flush (); objout. close (); fout. close (); fileinputstream fin = new fileinputstream (file_name); objectinputstream objin = new objectinputstream (FIN); testsub Ts = (testsub) objin. readobject (); objin. close (); Fin. close (); system. out. println (TS. name + "" + ts. age);} catch (exception ex) {ex. printstacktrace () ;}} public static void main (string [] ARGs) {New testexternalizable () ;}} class testsuper {string name = NULL; int age = 0; public void setname (string name) {This. name = Name;} public void setage (INT age) {This. age = age;} public void readexternal (objectinput) {try {name = (string) objectinput. readobject (); age = objectinput. readint ();} catch (exception ex) {ex. printstacktrace () ;}} public void writeexternal (objectoutput) {try {objectoutput. writeobject (name); objectoutput. writeint (AGE);} catch (exception ex) {ex. printstacktrace () ;}} class testsub extends testsuper implements externalizable {public testsub (){}}

H. If you write twice in an open stream, it will not be saved for the second time.ObjectOutputStream.reset()Method.

 

Author: gnuhpc

Source: http://www.cnblogs.com/gnuhpc/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.