Java serialization serializable and externalizable

Source: Internet
Author: User

Paper on the end of the light, I know this matter to preach-Lu He asked the canal that is clear, for Fountainhead-Zhu Xi

What is Java serialization? Why does Java serialization occur? How do I implement Java serialization? What is Java serialization Java serialization is the process of converting a Java object into a sequence of bytes, while Java deserialization refers to the process of reverting a sequence of bytes to a Java object.


Second, why the advent of Java serialization of two processes to communicate between the need to transfer a variety of information. For example, text, images, sounds, etc., which are transmitted in the form of a binary stream.

Is it possible to pass object data between processes? The answer is to be able. The serialization and deserialization of Java is the conversion of a Java object into a sequence of bytes that is transmitted over the network. Deserializes the resulting byte sequence data into the object.
Third, how to implement Java serialization
1), the input and output of the object: Objectinputstream,objectoutputstream. 2), object to implement serializable or Externalizable interface. Otherwise, an exception is thrown.
Note: Member data declared in serializable as static and transient types cannot be serialized.
To implement the serialization and deserialization of the Serializable Interface Demo sample program:
Public classStudentImplementsserializable{PrivateStringname;Private CharSex; PublicStudent () {} PublicStudent (String name, CharSex) { This.name= Name; This.Sex= Sex;    }Public voidSetName(String name) { This.name= Name;    }Public voidSetsex(CharSex) { This.Sex= Sex;    } PublicStringGetName()    {return This.name;    }Public CharGetsex()    {return This.Sex;    }}Public classusestudent{Public static voidMain(string[] args) {Student St =NewStudent ("Tom",' M ');        File File =NewFile ("O:\\Java\\com\\Jieke\\io\\Student.txt ");Try        {File.createnewfile ();        }Catch(IOException e) {E.printstacktrace ();        }Try        {//studentObject Serialization Process            FileOutputStream fos =NewFileOutputStream (file);            ObjectOutputStream Oos =NewObjectOutputStream (FOS);            Oos.writeobject (ST);            Oos.flush ();            Oos.close ();            Fos.close ();            //studentObject Deserialization Process            FileInputStream FIS =NewFileInputStream (file);            ObjectInputStream Ois =NewObjectInputStream (FIS);            Student st1 = (Student) ois.readobject ();            System. out. println ("name ="+ St1.getname ());            System. out. println ("sex ="+ St1.getsex ());            Ois.close ();            Fis.close ();        }Catch(ClassNotFoundException e) {E.printstacktrace ();        }Catch(IOException e) {E.printstacktrace ();        }    }}

Use the Externalizable interface for serialization. Must be rewrittenwriteexternal (objectoutput output)and thereadexternal (objectinput input)MethodThe serialization method using this interface needs to be implemented by us. This enables the serialization of static and transient data .

Public classPersonImplementsexternalizable {private static final longSerialversionuid= -842029427676826563L;Public StaticStringname;private int Age;private transient intWorkDay=5;PrivateStringFclub; PublicPerson () {System. out. println ("None-arg Constructor");    } PublicPerson (intAge, String fclub) { This. Age= Age; This.Fclub= Fclub;    }public intGetage() {return Age;    }Public voidSetage(intAge) { This. Age= Age;    }public intGetworkday() {returnWorkDay;    }Public voidSetworkday(intWorkDay) { This.WorkDay= WorkDay;    } PublicStringGetfclub() {returnFclub;    }Public voidSetfclub(String Fclub) { This.Fclub= Fclub;    }private voidwriteobject(ObjectOutputStream out)throwsIOException {out.defaultwriteobject ();//Run the default serialization mechanism        Out.writeint (WorkDay);        System. out. println ("sequence persistence is in progress");    }private voidReadObject(ObjectInputStream in)throwsIOException,            classnotfoundexception {in.defaultreadobject ();        WorkDay= In.readint ();        System. out. println ("Reading persisted objects");    }@Override    Public voidreadexternal(ObjectInput arg0)throwsIOException,            classnotfoundexception {// TODO auto-generated Method Stub    }@Override    Public voidwriteexternal(ObjectOutput arg0)throwsIOException {// TODO auto-generated Method Stub    }}Public classHello {Public static voidMain(string[] args) {Person person =NewPerson ( -, "Juventus");        Person.setworkday (7);Try{FileOutputStream fs =NewFileOutputStream ("Foo.ser");            ObjectOutputStream OS =NewObjectOutputStream (FS);            Os.writeobject (person);            Os.close ();            Person.name="Alex";            FileInputStream in =NewFileInputStream ("Foo.ser");            ObjectInputStream s =NewObjectInputStream (in);            Person P = (person) s.readobject ();            System. out. println ("name=="+ person.name+"age=="+ p.getage () +"workday=="+ p.getworkday () +"fclub=="+ P.getfclub ());        }Catch(Exception e) {E.printstacktrace ();        }    }}
There are, of course, a lot of open source serialization and deserialization libraries. Can be used in real project.

Java serialization serializable and externalizable

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.