Reference of Java serialization and serialization method of transitent

Source: Internet
Author: User
Tags class manager

ZZ from http://www.javaeye.com/topic/71035 Writer:Jonsamwang

In short, serialization is a mechanism used to process object streams. The so-called object stream is to stream the object content. The concept of stream is needless to say (I/O ), we can perform read and write operations on the converted objects or transmit the streaming objects between networks (Note: To transfer objects to the network, they must be streamed )! Some problems may occur when performing read/write operations on Object streams, and the serialization mechanism is used to solve these problems!

Question:

As mentioned above, what are the problems with reading and writing objects? For example, is there any problem if I want to write an object to a disk file and then read it out? Don't worry, one of the biggest problems is the object reference! For example, if I have two classes, A and B, and Class B contains a reference pointing to a class object, now we instantiate the two classes {A = new A (); B = new B () ;}. in this case, two spaces are actually allocated in the memory, one storage object A and one storage object B. Next we want to write them into a file on the disk, so there is a problem when writing the file! Because object B contains a reference to object A, the system automatically copies the data of object A to object B, in this case, when we restore an object from the file (that is, re-load the object to the memory), the memory allocates three spaces, and object A has two copies in the memory at the same time, think about the consequences. If I want to modify the data of object A, it is not necessary to search for every copy of the object to achieve the consistency of object data. This is not what we want!

Solutions for the following serialization mechanism:

1. All objects saved to the disk obtain a serial number (1, 2, 3, etc.) <Note: The serial number here should not be serialversionuid>

2. When you want to save an object, first check whether the object is saved.

3. If you have saved the object before, you only need to write the tag "Same as the object with serial number x already saved". Otherwise, save the object.

The above serialization mechanism solves the problem of object reference!

Serialization implementation:

The serializable interface is implemented for the class to be serialized. There is no method to implement this interface. implements serializable only aims to mark that the object can be serialized and then uses an output stream (such: fileoutputstream) to construct an objectoutputstream (Object stream) object. Then, you can use the writeobject (Object OBJ) method of the objectoutputstream object to write (that is, save its status) the object whose parameter is obj ), the input stream is used for recovery.

Example:

Import java. Io .*;

Public class test
{
Public static void main (string [] ARGs)
{
Employee Harry = new employee ("Harry hacker", 50000 );
Manager manager1 = new manager ("Tony tester", 80000 );
Manager1.setsecretary (Harry );

Employee [] Staff = new employee [2];

Staff [0] = Harry;
Staff [1] = manager1;
Try
{
Objectoutputstream out = new objectoutputstream (
New fileoutputstream ("employee. dat "));
Out. writeobject (staff );
Out. Close ();

Objectinputstream in = new objectinputstream (
New fileinputstream ("employee. dat "));
Employee [] newstaff = (employee []) in. readobject ();
In. Close ();

/**
* Raise salary through Harry objects
* Will be reflected in Secretary
*/
Newstaff [0]. raisesalary (10 );

For (INT I = 0; I <newstaff. length; I ++)
System. Out. println (newstaff [I]);
}
Catch (exception E)
{
E. printstacktrace ();
}
}

}

Class employee implements serializable
{
Public Employee (string N, double S)
{
Name = N;
Salary = s;
}

/**
* Salary increase
*/
Public void raisesalary (double bypercent)
{
Double raise = salary * bypercent/100;
Salary + = raise;
}

Public String tostring ()
{
Return getclass (). getname ()
+ "[Name =" + name
+ ", Salary =" + salary
+ "]";
}

Private string name;
Private double salary;
}

Class manager extends employee
{
Public Manager (string N, double S)
{
Super (N, S );
Secretary = NULL;
}

/**
* Set the secretary
*/
Public void setsecretary (employee s)
{
Secretary = s;
}

Public String tostring ()
{
Return super. tostring ()
+ "[Secretary =" + Secretary
+ "]";
}

// Secretary stands for Secretary
Private employee Secretary;
}

Modify the default serialization mechanism:

In the serialization process, we do not want to serialize some data fields. For such fields, we only need to add the transient keyword to them during definition, the transient field serialization mechanism will skip and will not write it into the file. Of course, it cannot be recovered. But sometimes we want to serialize a field, but its definition in the SDK is a non-serializable type, so we must mark it as transient, but how can we recover data that cannot be written? Fortunately, the serialization mechanism provides the following method definitions for classes that contain such special problems:

Private void readobject (objectinputstream in) throws

Ioexception, classnotfoundexception;

Private void writeobject (objectoutputstream out) throws

Ioexception;

(Note: These methods must be private when defined, because you do not need to display the call, the serialization mechanism will automatically call)

With the above method, we can manually write and read data fields that you want to serialize but cannot be serialized.

The following is a typical example: Java. AWT. point2d in the Geom package. the double class is not serializable because it does not implement the serializable interface. In my example, we will treat it as a data field in the labeledpoint class and demonstrate how to serialize it!

Import java. Io .*;
Import java. AWT. Geom .*;

Public class transienttest
{
Public static void main (string [] ARGs)
{
Labeledpoint label = new labeledpoint ("book", 5.00, 5.00 );
Try
{
System. Out. println (Label); // before writing
Objectoutputstream out = new objectoutputstream (New
Fileoutputstream ("label.txt "));
Out. writeobject (Label );
Out. Close ();

System. Out. println (Label); // After writing

Objectinputstream in = new objectinputstream (New
Fileinputstream ("label.txt "));
Labeledpoint label1 = (labeledpoint) in. readobject ();
In. Close ();
System. Out. println (label1); // read and add 1.0
}
Catch (exception E)
{
E. printstacktrace ();
}
}

}

Class labeledpoint implements serializable
{
Public labeledpoint (string STR, double X, Double Y)
{
Label = STR;
Point = new point2d. Double (x, y );
}

Private void writeobject (objectoutputstream out) throws ioexception
{
/**
* The defaultwriteobject () method must be called to write data.
* Object Description and serializable Fields
*/
Out. defaultwriteobject ();
Out. writedouble (point. getx ());
Out. writedouble (point. Gety ());
}

Private void readobject (objectinputstream in)
Throws ioexception, classnotfoundexception
{
/**
* The defaultreadobject () method must be called.
*/
In. defaultreadobject ();
Double X = in. readdouble () plus 1.0;
Double Y = in. readdouble () + 1.0;
Point = new point2d. Double (x, y );
}

Public String tostring ()
{
Return getclass (). getname ()
+ "[Label =" + label
+ ", Point. getx () =" + point. getx ()
+ ", Point. Gety () =" + point. Gety ()
+ "]";
}

Private string label;
Transient private point2d. Double point;
}

 

Related Article

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.