Understanding and learning of Java serialization

Source: Internet
Author: User

1. What is Java serialization

The Java platform allows us to create reusable Java objects in memory, but in general, these objects can exist only when the JVM is running, that is, they will not have a longer life cycle than the JVM. In a real-world application, however, it is possible to require that the specified object be saved (persisted) after the JVM has stopped running, and that the saved object will be re-read in the future. The serialization of Java objects can help us implement this functionality.

It is important to note that object serialization holds the "state" of the object, which is its member variable. It is to be concluded that object serialization does not focus on static variables in the class.

The so-called serialization is actually the data (objects) in the program in some way, saved to the local. The process of converting a Java object into a sequence of bytes is called serialization of the object. Just like you send a box of biscuits, because the volume is too large, it is all pressed into a powder tightly sent out, this is the role of serialization. However, the serialization of Java can be completely restored.

2. Where to use Java serialization

A) When you want to save the 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;

3. Serializing instances

Simpleserial is a simple serializer that saves a person object to a file person.out, and then reads the stored person object from the file and prints the object.

     Public classsimpleserial { Public Static voidMain (string[] args)throwsException {File file=NewFile ("Person.out"); ObjectOutputStream oout=NewObjectOutputStream (Newfileoutputstream (file)); Person Person=NewPerson ("John", 101, Gender.male);              Oout.writeobject (person);                   Oout.close (); ObjectInputStream oin=NewObjectInputStream (Newfileinputstream (file)); Object Newperson= Oin.readobject ();//no cast to person typeOin.close ();          System.out.println (Newperson); }      } 

The result of the above program output is:

    Arg constructor      

When the person object is saved to the Person.out file, we can read the file elsewhere to restore the object, but you must ensure that the classpath of the reader contains Person.class ( Even if the person class is not displayed when reading the person object, as in the example above, ClassNotFoundException will be thrown.

When serializing an object, it not only serializes the current object itself, but also serializes other objects referenced by the object, as well as other objects referenced by those other objects, and so on. Therefore, if an object contains member variables that are container class objects, and the containers contain elements that are also container class objects, the serialization process is more complex and expensive. When a field is declared as transient, the default serialization mechanism ignores the field.

4. Methods of serialization

Default serialization mechanism: implements the Serializable interface. When a field is declared as transient, the default serialization mechanism ignores the field.

With the Externalizable interface, Externalizable inherits from Serializable, and when the interface is used, the details of the serialization need to be done by the programmer. When using externalizable for serialization, when the object is read, the parameterless constructor of the serialized class is called to create a new object, and then the values of the fields of the saved object are populated into the new object, respectively. Therefore, a class that uses this interface requires a constructor for the public that has no parameters.

5. Serialization in a singleton mode

The person object obtained from file person.out is not equal to the singleton object in the person class. In order to be able to maintain the characteristics of a singleton during the serialization process, you can add a readresolve () method to the person class to return the singleton object of person directly, as follows:

    public class Person implements Serializable {               private static class Instanceholder {              private static final person in Statnce = new Person ("John", Gender.male);          }               public static Person getinstance () {              return instanceholder.instatnce;          }               Private String name = NULL;               Private Integer age = null;               Private Gender Gender = null;               Private person () {              System.out.println ("None-arg constructor");          }               Private person (String name, Integer age, Gender Gender) {              System.out.println ("Arg constructor");              this.name = name;              This.age = age;              This.gender = gender;          }               Private Object Readresolve () throws Objectstreamexception {              return instanceholder.instatnce;          }          ...      

6. Considerations for serialization

Need security considerations, such as an object has Private,public and other fields, for a transmission of objects, such as writing to a file, or RMI transmission, etc., in the process of serialization, the object's private domain is not protected.

Why are you suddenly interested in learning about serialization because of the exposure to Gson. Here Mark Gson and JSON.

Gson differs from other existing Java JSON class libraries when Gson need to serialize an entity class without using annotation to identify the fields that need to be serialized, and Gson can flexibly configure the fields that need to be serialized by using annotation.

New Gson (); ListNew arraylist<person>();  for (int i = 0; i <; i++new person ();p. SetName ("name" +* 5= GSO N.tojson (persons);

The above code focuses on the Gson object, which provides the Tojason () method to convert the object to a JSON string, the value of the Str object of the above code is:

[{' name ': ' NAME0 ', ' age ': 0},{' name ': ' name1 ', ' age ': 5},{' name ': ' name2 ', ' age ': 10},{' name ': ' Name3 ', ' age ': 15},{' name ' : ' Name4 ', ' age ': 20},{' name ': ' Name5 ', ' age ': 25},{' name ': ' Name6 ', ' age ': 30},{' name ': ' Name7 ', ' age ': 35},{' name ': ' Name8 "," Age ": 40},{" name ":" Name9 "," Age ": 45}]

The following is a look at the deserialization of Gson, Gson provides the Fromjson () method for implementing a method from a JSON-related object to a Java entity.

In everyday applications, we typically encounter two situations, turning into a single entity object and converting it into a list of objects or other structures.

Let's look at the first type:

For example, the JSON string is: [{"Name": "NAME0", "Age": 0}]

Person person = Gson.fromjson (str, person.  Class);

Provides two parameters, the JSON string, and the type of object that needs to be converted.

Second, convert to list type:

New Typetoken<list<person>>() {}.gettype ());  for (int i = 0; i < ps.size (); i++= ps.get (i); System.out.println (P.tostring ());}

You can see that the code above uses TypeToken, which is a data type converter provided by Gson, and can support a variety of data collection type conversions.

The above for my study notes, for reference on the Internet, a number of content, not specified, hereby thank you.

Understanding and learning of Java serialization

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.