Java uses serializable for serialization and deserialization implements object Clone (clone) __ Serialization

Source: Internet
Author: User

I believe many students have used serializable, I believe in the project in general your project manager and you said remember in your domain class to implement serializable, or sometimes there will be some errors. But what exactly does serializable do? Why do we have to achieve him. What role does he have? Serializable

The so-called serialization is to keep the object in binary form in the media you need to achieve the purpose of permanent preservation.
There is a serialization then there must be deserialization, otherwise the light can not be taken and what is the significance of it. deserialization is the process of fetching and converting a well serialized binary content back to an object.
The concept of light said students may be very forced, we directly on the demo. Demo1 (Permanently save object)

Requirements: The user object content is permanently saved to the hard disk and can be removed at any time.
Implementation: 1. Create the user class (be sure to implement serializable, otherwise it will be an error)

Import java.io.Serializable;

/**
 * Created by Beyondli on 2017/6/7.
 *

/public class User implements serializable{
    private String name;
    Private Integer age;

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    Public Integer Getage () {return age
        ;
    }

    public void Setage (Integer age) {
        this.age = age;
    }

    @Override public
    String toString () {return
        "user{" +
                "name= '" + name + ' \ ' +
                ", age=" + Age +
                " }';
    }
}
2. To serialize
    Serialization Test
    @Test public
    void Serializabletest () throws Exception {
        //Create a User object and assign it to
        user user = new user ();
        User.setname ("Beyondli");
        User.setage (a);
        Create content locations, paths, and files create a file file
        = new file ("H:\\test.txt") in advance;
        FileOutputStream fos = new FileOutputStream (file);
        Begins serialization of
        objectoutputstream Oos = new ObjectOutputStream (FOS);
        Oos.writeobject (user);
        Oos.flush ();
        Oos.close ();
        Fos.close ();
    }

The file is generated after execution, as follows

MMP, what the hell is this? I can't read it. This is the serialized content, I can not understand. But other people's computers can read and understand. 3. Deserialize the value of

    The deserialization test
    @Test public
    void SerializableTest2 () throws Exception {
        //Gets the file containing the binary content, filename
        = new File (" H:\\test.txt ");
        FileInputStream fis = new FileInputStream (file);
        Begins deserialization of
        objectinputstream ois = new ObjectInputStream (FIS);
        Remove the deserialized content and strongly convert the
        user user = (user) Ois.readobject ()
        to the object we want to encapsulate. SYSTEM.OUT.PRINTLN (user);
        Ois.close ();
        Fis.close ();
    }
4. Operating results


We will find that the objects we have serialized have been taken out directly by us. This allows us to permanently save the object's contents through serialization. 5. If the user object does not implement the serialization interface, it will be wrong in the Run-time times


Obviously tell you serializable exception Demo2 (object cloning)

Requirements: Use serialization and deserialization to clone the user object and modify the cloned data. 1. Create User

Import java.io.Serializable;

/**
 * Created by Beyondli on 2017/6/7.
 *

/public class User implements serializable{
    private String name;
    Private Integer age;

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    Public Integer Getage () {return age
        ;
    }

    public void Setage (Integer age) {
        this.age = age;
    }

    @Override public
    String toString () {return
        "user{" +
                "name= '" + name + ' \ ' +
                ", age=" + Age +
                " }';
    }
}
2. Writing the Cloning tool class
Package com.beyondli.base.utils;

Import java.io.*;

/**
 * Created by Beyondli on 2017/6/8.
 * Object Clone Tool class */public
class Cloneutils {
    private cloneutils () {
        throw new Assertionerror ();
    }

    public static <t extends serializable> t clone (T obj) throws Exception {
        //Create a piece of memory to hold the object content
        Bytearrayoutputstream bout = new Bytearrayoutputstream ();
        ObjectOutputStream oos = new ObjectOutputStream (bout);
        Converts an object into binary content into an open memory (serialized)
        Oos.writeobject (obj);

        Read binary content in memory block
        bytearrayinputstream bin = new Bytearrayinputstream (Bout.tobytearray ());
        Converts binary content back to object deserialization
        objectinputstream ois = new ObjectInputStream (bin);
        Return (T) ois.readobject ();

    }
}
3. Test class
   @Test public
   void Clonetest () throws Exception {
        User user = new user ();
        User.setname ("Beyondli");
        User.setage (a);
        Cloning
        User clone = Cloneutils.clone (user) using serialization;
        Modifies one of the values of the cloned object
        clone.setname ("Zyt");
        Output
        System.out.println (user);
        System.out.println (clone);
    }
4. Operating results

The above is the understanding of some basic concepts of serializable and some practical applications. Content for my own understanding, if there are deficiencies or errors, I hope to point out. Grow together.

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.