Serializable Java serialization

Source: Internet
Author: User
Tags object serialization serialization sessions

The bean Serializable Interface interface allows the bean to serialize, turning it into a binary stream that can be saved for later use. When a bean is serialized to disk or anywhere else, its state is saved, and the value of the property does not change. In the bean's specification, the JSP does not require the bean to implement the serializable interface. However, if you want to control the serialization process of the components you create, or you want to serialize components that are not standard component extensions, you must understand the details of serialization and deserialization.

There are several reasons why you can refrigerate the beans for later use. Some servers support any long session lifetime by writing all of the sessions data (including beans) to disk, even if server downtime is not lost. When the server restarts, the serialized data is restored. For the same reason, in environments that support server clustering on heavily-loaded sites, many servers replicate sessions through serialization. If your bean does not support serialization, the server will not be able to save and transfer the classes correctly.

With the same strategy, you can choose to save the bean on disk or in the database for later use. For example, you might implement a customer's shopping cart as a bean and save it in a database during access.

If your bean requires special, complex initial settings, you can set the bean to be serialized and stored on disk. The "snapshot" of this bean can be used wherever it is needed, including in $#@60;jsp:usebean$#@62, with calls to the Beanname property.

The Beanname property in the $#@60;jsp:usebean$#@62 tab, which is used to instantiate a serialized bean instead of creating a completely new instance from a class. If the Bean has not yet been created, the Beanname property is passed to the Java.beans.Bean.instantiate () method, which is instantiated by the class loader. It first assumes that there is a serialized bean (with the extension. ser) and then activates it. If this operation fails, it instantiates a new instance.




   Here is a brief introduction to this interface

Objects can contain other objects, and other objects can contain other objects. The JAVA serialization can automatically handle nested objects. For a simple domain of an object, WriteObject () writes the value directly to the stream. When an object field is encountered, the WriteObject () is called again, and if the object is embedded in another object, then the WriteObject () is invoked until the object can be directly written to the inflow. What the programmer needs to do is to pass the object into the ObjectOutputStream writeobject () method, and the rest will be automatically completed by the system. The following example creates a Personaldata object that invokes the mine object. The code does this by outputting a string and mine object to a stream and depositing it in a file:

public class Personaldata implements Serializable {
public int ID
public int Yearofbirth;
public float yearlysalary;
}
Personaldata mine = new Personaldata (101, 1956, 46500.00);
FileOutputStream OutStream = new FileOutputStream ("Personaldata.ser");
ObjectOutputStream out = new ObjectOutputStream (OutStream);
Out.writeobject ("My personal Data"); Writes a string to the stream
Out.writeobject (mine); Writes this object to the stream
Out.close (); Clear and close the stream
...

A FileOutputStream object is created and passed to a objectoutputstream. When Out.writeobject () is invoked, this string and the mine object are added to a byte pair column that is stored in the file Serializ objects are personaldata.ser order.

You should note that the above class is the implemented Java.io.Serializable interface. Because it does not specify the method to implement, serializable is called "tagging interface", but it only "tags" its own object is a special type. Any object you want to serialize should implement this interface. This is a must. Otherwise, the flow technology will not work at all. For example, if you try to serialize an object that does not implement this interface, a notserializableexception will be generated.

Class enables its serialization functionality by implementing the Java.io.Serializable interface. A class that does not implement this interface will not be able to serialize or deserialize any of its states. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and is used only to identify serializable semantics.

Java object serialization allows you to convert an object that implements the serializable interface into a set of byte, so that when you use the object later, you can recover the byte data and reconstruct the object accordingly.

To serialize an object, you must first create a outputstream and then embed it in ObjectOutputStream. At this point, you can use the WriteObject () method to write the object to the OutputStream.

The WriteObject method is responsible for writing the state of the object of a particular class so that the corresponding ReadObject method can restore it. By calling Out.defaultwriteobject, you can invoke the default mechanism for fields that hold Object. The method itself does not need to involve states that belong to its superclass or subclass. States are saved by writing each field to ObjectOutputStream by using the WriteObject method or by using a method supported by DataOutput for the base data type.

When you read, you have to embed the inputstream inside the ObjectInputStream, and then call the ReadObject () method. But this read out, is only an object reference, so before using, still have to pass first. The ReadObject method is responsible for reading and restoring class fields from the stream. It can call the In.defaultreadobject to invoke the default mechanism to restore the non-static and non transient fields of the object.

The Defaultreadobject method uses the information in the stream to allocate fields in the stream that are saved by the corresponding named fields in the current object. This is used to handle the situation where new fields need to be added after class development. The method itself does not need to involve states that belong to its superclass or subclass. States are saved by writing each field to ObjectOutputStream by using the WriteObject method or by using a method supported by DataOutput for the base data type.

Look at a:
Import java.io. * ;

Class Tree implements Java.io.Serializable {
Public tree left;
The public is right;
public int id;
public int level;

private static int count = 0;

Public tree (int depth) {
ID = count + +;
level = depth;
if (Depth > 0) {
left = new Tree (depth-1);
right = new tree (depth-1);
}
}

public void print (int levels) {
for (int i = 0; i < level; I + +)
System.out.print ("");
System.out.println ("node" + ID);

If (level <= levels && left!= null)
Left.print (levels);

If (level <= levels && right!= null)
Right.print (levels);
}


public static void Main (String argv[]) {

try {
/**//* Creates a file to write to the serialization tree. */
FileOutputStream ostream = new FileOutputStream ("tree.tmp");
/**//* Create output stream * *
ObjectOutputStream p = new ObjectOutputStream (ostream);

/**//* Create a two-layer tree. */
Tree base = new Tree (2);

P.writeobject (base); Writes the tree to the stream.
P.writeobject ("LiLy is the Southland");
P.flush ();
Ostream.close (); Closes the file.

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.