Serialization and deserialization of Java

Source: Internet
Author: User
Tags base64 class definition object serialization

1)Java serialization is the conversion of an object into a sequence of bytes, while the Java deserialization is the restoration of a sequence of bytes to a Java object.

2) The use of Java serialization and deserialization technology, one can achieve the persistence of data, in the MVC pattern is very useful, and the other is the object data can be remote communication.

1. What is serialization?
This is simply to preserve the state of various objects in memory (i.e., instance variables, not methods), and to read the saved object state again. Although you can use your own various methods to save the object states, butJava provides you with a mechanism that should be better than your own to preserve the state of the object, which is serialization.
2. What situations require serialization
a) When you want to save the state of an object in memory in a file or in a database;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI;

6.Related precautions
A when serializing, only the state of the object is saved, regardless of the object's method;
b) When a parent class is serialized and the subclass is automatically serialized, no explicit implementation of the serializable interface is required;
c) When an instance variable of an object refers to another object, the object is serialized as well.
D) Not all objects can be serialized, and there are a number of reasons why not
.
Like what:
1. Security reasons, such as an object has Private,public and other fields, for a transmission of the object, such as writing to a file, or RMI transmission, etc., during the serialization of the transfer process, the object's private domain is not protected.
2. Resource allocation reasons, such as the Socket,thread class, can be serialized, transmitted or saved, and cannot be re-allocated, and there is no need to implement this.
Detailed Description:
The process of serialization is that the object writes the byte stream and reads the object from the byte stream. After you convert the object state into a byte stream, you can use theThe various byte stream classes in the Java.io package save it to a file, pipe to another thread, or send object data to another host over a network connection. The object serialization feature is simple and powerful, with applications in RMI, sockets, JMS, and EJBs. Object serialization problem is not the most exciting topic in network programming, but it is very important and has many practical meanings.
One: Object serialization can implement distributed objects. Main applications For example: RMI to use object serialization to run a service on a remote host, just as you would when running an object on a local machine.
Two:Java object serialization preserves not only the data of an object, but also the data of each object referenced by the object. You can write the entire object hierarchy to a stream of bytes that can be saved in a file or passed on a network connection. Object serialization allows you to "deep copy" the object, which is to copy the object itself and the referenced object itself. Serializing an object may get the entire sequence of objects.
From the above narrative, we know that object serialization isThe necessary weapon in Java programming, so let's start with the basics and learn about its mechanics and usage.
Java serialization is relatively straightforward and typically does not require writing custom code to save and restore object state. RealizeThe class object of the Java.io.Serializable interface can be converted into a byte stream or recovered from a byte stream, without the need to add any code to the class. Only rare cases require custom code to save or Restore object state. Note here that not every class can be serialized, and some classes cannot be serialized, such as a thread-related class with a very complex relationship to a particular JVM.
Serialization mechanism:
Serialization consists of two parts: serialization and deserialization.serialization is the first part of this process that decomposes data into a byte stream for storage in a file or on a network. Deserialization is the opening of a byte stream and refactoring the object. Object serialization not only converts the base data type to a byte representation, but sometimes restores the data. Recovering data requires an object instance that has recovery data.The serialization process in ObjectOutputStream is connected to a byte stream, including object type and version information.When deserializing, the JVM generates an object instance with header information and then copies the data in the object stream into the object data member. Here we have two parts to illustrate:
To process the object flow:
(Serialization process and deserialization process)
The Java.io package has a class of two serialized objects. The ObjectOutputStream is responsible for writing the object to the byte stream, ObjectInputStream the object from the byte stream.
Let's get to know the ObjectOutputStream class first. The ObjectOutputStream class extends the DataOutput interface.
The WriteObject () method is the most important method for object serialization. If the object contains references to other objects, the WriteObject () method recursively serializes the objects. Each ObjectOutputStream maintains a serialized object reference table, preventing multiple copies of the same object from being sent. (This is important) because WriteObject () can serialize an entire set of cross-referenced objects, so the same ObjectOutputStream instance may be accidentally requested to serialize the same object. At this point, the deserialization is serialized instead of being written to the object byte stream again.
Let's take a look at the ObjectOutputStream class from the examples below.
Serialize today's date into a file.
FileOutputStream f = new FileOutputStream ("TMP"); Create a "TMP" data file that contains the recovery object (that is, the object is deserialized information)
ObjectOutputStream s = new ObjectOutputStream (f);
S.writeobject ("Today"); Writes a String object;
S.writeobject (New Date ()); Writes a transient object;
S.flush ();
Now, let's get to know the ObjectInputStream class. It is similar to ObjectOutputStream. It extends the Datainput interface. ObjectInputStream method in the mirror DataInputStream read inThe public method of the Java base data type. The ReadObject () method deserializes an object from a byte stream. Each call to the ReadObject () method returns the next object in the stream.The object byte stream does not transmit the class's bytecode, but includes the class name and its signature. ReadObject () When an object is received, the JVM loads the class specified in the header. If this class is not found, then ReadObject () throws ClassNotFoundException, and if you need to transfer object data and bytecode, you can use the RMI framework. The remaining methods of ObjectInputStream are used to customize the deserialization process.
Examples are as follows:
Deserializes a string object and a Date object from a file
FileInputStream in = new FileInputStream ("TMP");
ObjectInputStream s = new ObjectInputStream (in);
String today = (string) s.readobject (); Recover objects;
Date date = (date) s.readobject ();
To customize the serialization process:
Serialization can usually be done automatically, but this process can sometimes be controlled.Java can declare a class as serializable, but it can still manually control data members that are declared static or transient.
Example: A very simple serialization class.
public class Simpleserializableclass implements serializable{
String stoday= "Today:";
Transient date dttoday=new date ();
}
When serializing, all data members of a class should be serializable except for members declared as transient or static. Declaring a variable as transient tells the JVM that we are responsible for serializing the arguments. After a data member is declared as transient, the serialization process cannot add it to the object byte stream, and no data is sent from the transient data member. When the data is deserialized, the data member is rebuilt (because it is part of the class definition) but does not contain any data because the data member does not write any data to the stream. Remember that the flow of objects does not serialize static or transient. Our classes use the WriteObject () and ReadObject () methods to process these data members. When using the WriteObject () and ReadObject () methods, also note that these data members are read in the order in which they are written.
Some of the code on how to use custom serialization is as follows:
Override the WriteObject () method to handle the members of the transient.
public void WriteObject (ObjectOutputStream outputstream) throws ioexception{
Outputstream.defaultwriteobject ();//enable the custom WriteObject () method to
Take advantage of the logic built into automatic serialization.
Outputstream.writeobject (Osocket.getinetaddress ());
Outputstream.writeint (Osocket.getport ());
}
Override the ReadObject () method to receive members of the transient.
private void ReadObject (ObjectInputStream inputstream) throws ioexception,classnotfoundexception{
Inputstream.defaultreadobject ();//defaultreadobject () Supplemental automatic serialization
InetAddress oaddress= (inetaddress) inputstream.readobject ();
int Iport =inputstream.readint ();
Osocket = new Socket (oaddress,iport);
Iid=getid ();
Dttoday =new Date ();
}

My problem is transmission over the Internet.

Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
Bitmap.compress (Bitmap.CompressFormat.PNG, BAOs);
String photodata = new String (Base64.encode (Baos.tobytearray (),
Base64.default));

This variable photodata can be transmitted over the network.

An example of Zhang's sister:

/** @author Zxq
* Serialization and deserialization processing
*/
public class Serializeutil {

Public final static String charset_iso88591= "Iso-8859-1";

/** @author Zxq
* Serialization of objects
* @param Original
* @return
* @throws IOException
*/
public static String Serialize (Object original) throws IOException {
if (null==original) return null;
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
ObjectOutputStream oos = new ObjectOutputStream (BAOs);
Oos.writeobject (original);
byte[] str = Baos.tobytearray ();
Oos.close ();
Baos.close ();
return new String (str,charset_iso88591);
}

/** @author Zxq
* Deserialization
* @param serializedstr
* @return
* @throws unsupportedencodingexception
* @throws IOException
* @throws ClassNotFoundException
*/
public static Object deserialize (String serializedstr) throws Unsupportedencodingexception, IOException, classnotfoundexception{
if (NULL==SERIALIZEDSTR) return null;
Bufferedinputstream bis=new Bufferedinputstream (New Bytearrayinputstream (serializedstr.getbytes) ));
ObjectInputStream ois = new ObjectInputStream (bis);
Object obj = Ois.readobject ();
Ois.close ();
Bis.close ();
return obj;
}

Serialization and deserialization of Java

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.