Object continues
Continuous (persistence) refers to the ability to record your own state so that the ability to regenerate in the future. For example, a continuous object may save its status in a file. This file can be used to restore this object in different operating environments. The object itself does not sustain, but the information required to construct the object replica continues. When the object is serialized, all object data writes stream, but its method and class definition do not write.
Why introduce a series of
Traditional mode (storage data to disk, etc.) Need to define a specific data format to write a function module that read and write the format data, which must establish a file format and maps between its own data formats, and read and write functions are either simple and missing. Complex is difficult to create and maintain. The life of the Java object is usually terminated with the program of generating the object, and the object may be terminated during operation. If the object in memory is temporary, that is, when they exceed the reference value (or range) or the system is turned off (such as dropping), they do not exist, while serialized objects as long as the disk, tape or other place There is a copy, it has always existed.
Object sequence
l Supports two-way communication between different versions running on different virtual machines
l Definition allows Java class to read the mechanism of data stream written with the same type of older version
l Define the mechanism of data streams that allow Java classes to be read with the same class more older versions
l Provides serialization of persistence and RMI
l Generate a compressed stream and well operating so that RMI can be serialized
l Is it a local stream?
l Keep low load of non-version types
Serialization
Serialization means that the object records its own procedure by writing a value that describes its own state, that is, to represent a series of ordered bytes, and Java provides a method of writing a stream and a recovery object from a stream. The main task of series is to write the value of the object instance variable. If the variable is a reference to another object, the referenced object is also serialized. This process is recursive, the series process may involve a series of complex number of structures, including the original object, object object, object object, and so on. The hierarchy of object ownership is a graphic.
Not all classes can be serialized, only objects that implement the SERIALIZABLE or Externalizable interface can successfully serialize. Both interfaces are in the java.io package. The serialized object is available to the external object series. It is actually an output stream. The specific object is to write its own state, and another object cannot do this.
The Java language object serialization supports its two main features. Java's RMI enables objects that are present in other machines, can show behaviors on the local machine. When sending a message to a remote object, you need to transmit parameters and return values through object serialization; the sequence of objects is also required for Java Beans. When using a bean, its status information is usually configured during design, after the program is started, This status information is saved by using object serialization so that the program is restored.
SERIALIZABLE interface
The Serializable interface itself does not include any method. When a class declares is to implement serializable, it is only a statement to participate in the serialized protocol. When the object is serialized, if the object status write flow, the stream should include sufficient information required to recover the object. Even if the recovered class modifies the updated compatible version, there is also enough information to restore the restoration.
Classes that meet the following conditions can be serialized:
One of the L-class or its superior categories should implement a java.io.Serializable interface;
The class L must have a method to control the stored data and add new data to existing data;
The class L must have the readObject () method to read the data written in the corresponding writeObject () method.
If the serialization class is a variable that does not want to serialize (such as password), you need to mark the keyword transient, that is, the temporary field will not be automatically saved by the defaultwriteObject () method, which must be explicitly saved and restored in the program. And the field is initialized inside the member, not in the definition, which ensures that they do not initialize some automation mechanisms when reassign. Many things such as static data, open the file handle, socket connection, and threads are unminerated. Externalizable interface
The Externalizable interface identifier can be stored in a flow but responsible for saving the object of its own state. When an avatar is written, this flow is only responsible for storing the class name of the object, and the object is to write its own data. The externalizable interface is defined as follows:
Public Interface Externalizable Extends Serializable {
Public void writeexternal (ObjectOutput out)
Throws oException;
Public void readExternal (ObjectInput in)
THROWS IOEXCEPTION, ClassNotFoundException;
}
The specificization class must follow this specification.
Object output stream
The object of other objects can be serially realized the ObjectOutput interface in the java.io package, which is defined as follows:
Public interface ObjectOutput Extends DataOutput {
Public void writeObject (Object Obj)
Throws oException;
Public Void Write (int b) THROWS IOEXCEPTION;
Public void write (byte b []) throws oException;
Public void write (byte b [], int OFF, int LEN)
Throws oException;
Public void flush () throws oException;
Public void close () throws oException;
}
The main method of this interface is WriteObject (Object Obj) to write the OBJ in the stream. Obj's static and temporary data is ignored, all other variables are written. ObjectOutput interface extension DataoutPUT interface, DataOutput method write to support write original data types. For example, the WriteDouble () method is written to Double type data, WriteBoolean () is written to Boolean data, these prototype type write methods to write prototype instance variables for objects.
When the object is to be serialized into a file, the first step is to establish an output stream with file communication:
FileOutputStream fo = new fileoutputstream ("obj.file");
Then generate the object output stream and link it to the file output stream:
ObjectOutputStream so = New ObjectOutputStream (fo);
The object output stream can be written in the stream with the WriteObject () method, such as the following encoding constructs the instance of the Point class and serializes it:
So.writeObject (New Point (15, 20));
SO.FLUSH ();
Reactionary
The ObjectInputStream class will serialize the stream of streamlined. The program uses this class to restore the series of objects from the entire object tree referred to by stream and primary objects, or the original data type can also be read from the object input.
Serialization
Six anomalies may be thrown during the series and anti-systemic objects:
InvalidClassexception typically throws this exception when it is unable to determine the type or the class returned when the type of resection is not determined. Exception also throws up when the recovered class does not declares or without public default (no meta) constructor. NotSerializableException is usually thrown by an input stream error by a particularized object (responsible for itself). Error is usually indicated by unexpected invariat values, or indicating that objects to be serialized are not serialized.
StreamcorruptedException throws when the header or control data is stored.
The OPTIONALDATAEXCEPTION stream should contain objects but actually only contain prototype data.
The ClassNotFoundException stream is not found when the category of the anti-system object is not found.
IOEXCEPTION is thrown when the object to be read or written.
Serialization example
1. Customized data format series
Verify how to encode a customized data format with WriteObject and ReadObject methods. When there is a lot of persistent data, the data should be stored in a concise, streamlined format. This example uses a rectangular symmetric array, only half of the data, ie, only write / read half of the data to restore to a complete array.
/*CustomDataexample.java * /
Import java.io. *;
Public class customDataexample1 imports serializable {
TRANSIENT INT DIMENSION;
Transient int theArray [] [];
CustomDataExample11 (INT DIM) {
Dimension = DIM;
THEARRAY = new int [DIM] [DIM];
Arrayinit ();
}
Public static void main (string args []) {
CustomDataExample1 Corg = New CustomDataExample1 (4);
CustomDataExample1 CNEW = NULL;
Try {
FileoutPutStream fo = new fileoutputstream ("cde.tmp");
ObjectOutputStream so = New ObjectOutputStream (fo);
So.writeObject (CORG);
SO.FLUSH ();
So.close ();
} catch (exception e) {
E.PrintStackTrace ();
System.exit (1);
}
Try {
FileInputStream Fi = New FileInputStream ("CDE.TMP");
ObjectInputStream Si = New ObjectInputStream (Fi);
CNEW = (CustomDataExample1) Si.ReadObject ();
Si.Close ();
} catch (exception e) {
E.PrintStackTrace ();
System.exit (1);
}
SYSTEM.OUT.PRINTLN ();
System.out.println ("Printing The Original Array ...");
System.out.println (CORG);
SYSTEM.OUT.PRINTLN ();
System.out.println ("Printing The New Array ...");
SYSTEM.OUT.PRINTLN ();
System.out.println (CNEW);
SYSTEM.OUT.PRINTLN ();
System.out.println ("The Original and New Arrays Should Be The Same!"); System.out.Println ();
}
Private void writeobject (ObjectOutputstream S) throws oException {
/ * First adjust the default defaultWriteObject () method to save non-challenge (if any) * /
s.defaultwriteObject ();
/ * Call the prototype data WriteInt () method to save its * /
S.WriteInt (DIMENSION);
For (INT i = 0; i For (int J = 0; j <= i; j ) { / * Specifically call the prototype data WriteInt () method to save half of its arrays * / S.WriteInt (THEARRAY [i] [j]); } } } Private Void ReadObject (ObjectInputStream S) THROWS IEXCEPTION, ClassNotFoundException { / * First in the default defaultReadObject () method to restore non-temporary data, reversely call the prototype data readint () method to restore the order of the temporary data, write, and recovery data, * / S.DEFAULTREADOBJECT (); Dimension = s.readint (); THEARRAY = New int [Dimension] [Dimension]; For (INT i = 0; i For (int J = 0; j <= i; j ) { THEARRAY [I] [J] = S.Readint (); } } For (INT i = 0; i For (int J = Dimension-1; J> i; J -) { THEARRAY [I] [J] = THEARRAY [J] [i]; } } } / * The function of this method is to make the array to a diagonal. * / Void arrayinit () { INT x = 0; For (INT i = 0; i For (int J = 0; j <= i; j ) { THEARRAY [I] [J] = x; THEARRAY [J] = x; X ; } } } Public string toString () { StringBuffer SB = new stringbuffer (); For (INT i = 0; i For (int J = 0; j SB.Append (Integer.Tostring (THEGER.TOSTRING (THEARRAY [I] [J]) "" } sb.append ("/ n"); } Return (sb.toString ()); } } The results are as follows: Printing the Original Array ... 0 1 3 6 1 2 4 7 3 4 5 8 6 7 8 9 Printing the New Array ... 0 1 3 6 1 2 4 7 3 4 5 8 6 7 8 9 The Original and New Arrays Should Be The Same! 2. Serialization of non-sequential superclass When a superclass of a serialized subclass is not serialized, the subclass must explicitly store the superclass status. / *Nonserialsuperexample.java * / Import java.io. *; Public class nonserialsuperexample { Public static void main (string args []) { Book bookorg = New book (100, "How to serialize", True, "R.R", "Serialization", 97); Book Booknew = NULL; Try { FileOutputStream fo = new fileoutputstream ("tmp"); ObjectOutputStream so = New ObjectOutputStream (fo); So.writeObject (Bookorg); SO.FLUSH (); } catch (exception e) { System.out.println (e); System.exit (1); } Try { FileInputStream Fi = New FileInputStream ("TMP"); ObjectInputStream Si = New ObjectInputStream (Fi); Booknew = (book) Si.ReadObject (); } catch (exception e) { System.out.println (e); System.exit (1); } System.out.println (); System.out.println ("Printing Original Book .."); System.out.println (Bookorg); System.out.println ("Printing New Book .."); System.out.println (Booknew); System.out.println ("Both Original and New Should Be The Same"); System.out.println (); } } / * Book.java * / Import java.io. *; Class Book Extends ReadingMaterial Implements Serializable { INT NUMPAGES; String name; Boolean ishardcover; Public book () {super (); Public Book (int pages, string n, boolean hardcover, string author, string subject, int yearwritten) { Super (Author, Subject, YearWritten); Numpages = Pages; Name = n; Ishardcover = Hardcover; } Private void writeObject (ObjectOutputStream out) throws ioException { Out.defaultwriteObject (); Out.writeObject (author); Out.writeObject (Subject); Out.writeint (YearWritten); } Private Void ReadObject (ObjectInputStream in) THROWS IEXCEPTION, ClassNotFoundException { In.DefaultReadObject (); Author = (string) in.readObject (); Subject = (string) in.readObject (); YearWritten = in.readint (); } Public string toString () { Return ("Name:" Name "/ N" "Author:" Author "/ N" "Pages:" Numpages "/ n" "Subject:" Subject "/ N" "Year:" YearWritten "/ n"); } } / * ReadingMaterial.java * / Import java.io. *; Import java.lang.string; Import java.io.externalizable; Import java.io.objectInput; Import java.lang.classNotfoundException; Import java.io.ioException; Import java.io.ObjectOutput; Class readingmaterial { Protected string author; Protected string subject; protected int yearwritten; Public ReadingMaterial () {} Public Readhuang (String Auth, String Sub, Int Year) { Author = auth; Subject = SUB; YearWritten = year; } } The results are as follows: Printing Original Book .. Name: how to serialize Author: r.r Pages: 100 Subject: Serialization Year: 97 Printing new book .. Name: how to serialize Author: r.r Pages: 100 Subject: Serialization Year: 97 Both Original and New Should Be The Same 3. The avatar specificity of super-class When an interface is used, a particularized object must run the WriteExternal () method to store the object's status to read the status of the object with the Readexternal method. This example verifies how to store and restore its status of the superclatrios. When a superclass that can be embodied objects is also particularized, the subcategory is to call the WriteExternal () and readExternal () method in its own WriteExternal () and ReadExternal () methods. /*SAVESUPER.JAVA * / Import java.io. *; Public class savesuper { Public static void main (string args []) { Book1 bookorg = New book1 (100, "How to serialize", true, "r.r", "serialization", 97); Book1 booknew = NULL; Try { FileOutputStream fo = new fileoutputstream ("tmp"); ObjectOutputStream so = New ObjectOutputStream (fo); So.writeObject (Bookorg); SO.FLUSH (); } catch (exception e) {system.out.println (e); System.exit (1); } Try { FileInputStream Fi = New FileInputStream ("TMP"); ObjectInputStream Si = New ObjectInputStream (Fi); Booknew = (book1) Si.ReadObject (); } catch (exception e) { System.out.println (e); System.exit (1); } System.out.println (); System.out.println ("Printing Original Book .."); System.out.println (Bookorg); System.out.println ("Printing New Book .."); System.out.println (Booknew); System.out.println ("Both Original and New Should Be The Same"); System.out.println (); } } / * Book1.java * / Import java.io. *; Class Book1 Extends ReadingMare1 Implements Externalizable { PRIVATE INT NUMPAGES; PRIVATE STRING NAME; Private boolean ishardcover; Public book1 () {super (); Public book1 (int Pages, String n, Boolean Hardcover, String Author, String Subject, Int YearWritten) { Super (Author, Subject, YearWritten); Numpages = Pages; Name = n; Ishardcover = Hardcover; } Public void witeexternal (ObjectOutput out) throws oException { Super.WriteExternal (OUT); /*Out.writeint (Numpages); * Out.writeObject (name); Out.writeBoolean (ishardcover); * / } Public void readexternal (Object Inputin) throws oException, classnotfoundexception { Super.Readexternal (in); Numpages = in.readint (); Name = (string) in.readObject (); ishardcover = in.readboolean (); } Public string toString () { Return ("Name:" Name "/ N" "Author:" Super.getAuthor () "/ N" "Pages:" Numpages "/ N" "Subject:" super.getsubject () "/ n" "year:" super.getyearwritten () "/ n"); } } / * ReadingMare1.java * / Import java.io. *; Import java.lang.string; Import java.io.externalizable; Import java.io.objectInput; Import java.lang.classNotfoundException; Import java.io.ioException; Import java.io.ObjectOutput; Class ReadingMare1 Implements Externalizable { Private string author; PRIVATE STRING SUBJECT; Private int yearwritten; Public ReadingMare1 () {} Public ReadmateriAl1 (String Auth, String Sub, Int Year) { Author = auth; Subject = SUB; YearWritten = year; } Public string getAuthor () { Return author;} Public string getSubject () { Return Subject;} Public int getYearWritten () { Return Yearwritten;} Public void writeexternal (ObjectOutput out) throws oews { Out.writeObject (author); Out.writeObject (Subject); Out.writeint (YearWritten); } Public Void Readexternal (ObjectInput in) THROWS IOEXCEPTION, ClassNotFoundException { Author = (string) in.readObject (); Subject = (string) in.readObject (); YearWritten = in.readint (); } } The results are as follows: Printing Original Book .. Name: how to serialize Author: r.r Pages: 100 Subject: Serialization Year: 97 Printing new book .. Name: NULL Author: r.r Pages: 0 Subject: Serialization Year: 97 Both Original and New Should Be The Same 4. Non-specific superclass avatar When an interface is used, a particularly object must run the WriteExternal () method to store the status of the object with the readExternal () method to read the status of the object. This example verifies how an object stores and restores its non-body hyperclass. When a superclass that can be embodied objects is not particularized, the subclass must use its own WriteExternal () and readExternal () methods to explicitly store and restore its superclatrios. / * NonexternSuper1.java * / Import java.io. *; Public class nonexternsuper1 { Public static void main (string args []) { Book2 bookorg = New book2 (100, "How to serialize", True, "R.R", "Serialization", 97) Book2 booknew = NULL; Try { FileOutputStream fo = new fileoutputstream ("tmp"); ObjectOutputStream so = new ObjectOutputStream (fo); So.writeObject (Bookorg); SO.FLUSH (); } catch (exception e) { System.out.println (e); System.exit (1); } Try { FileInputStream Fi = New FileInputStream ("TMP"); ObjectInputStream Si = New ObjectInputStream (Fi); Booknew = (book2) Si.ReadObject (); } catch (exception e) { System.out.println (e); System.exit (1); } System.out.println (); System.out.println ("Printing Original Book .."); System.out.println (Bookorg); System.out.println ("Printing New Book .."); System.out.println (Booknew); System.out.println ("Both Original and New Should Be The Same"); System.out.println (); } } / * Book2.java * / Import java.io. *; Class Book2 Extends ReadingMaterial2 Implements Externalizable { INT NUMPAGES; String name; Boolean ishardcover; Public book2 () {super (); Book2 (Int Pages, String N, Boolean Hardcover, String Author, String Subject, Int YearWritten) { Super (Author, Subject, YearWritten); Numpages = Pages; Name = n; Ishardcover = Hardcover; } Public void writeexternal (ObjectOutput out) throws oews { Out.writeObject (author); Out.writeObject (Subject); Out.writeint (YearWritten); Out.writeint (Numpages); Out.writeObject (name); Out.writeBoolean (ishardcover); } Public void readExternal (ObjectInput in) THROWS IEXCEPTION, ClassNotFoundException { Author = (string) in.readObject (); Subject = (string) in.readObject (); YearWritten = in.readint (); Numpages = in.readint (); Name = (string) in.readObject (); ishardcover = in.readboolean (); } Public string toString () { Return ("Name:" Name "/ N" "Author:" Author "/ N" "Pages:" Numpages "/ N" "Subject:" Subject "/ N" "Year:" YearWritten "/ n");} } / * ReadingMaterial2.java * / Import java.io. *; Import java.lang.string; Import java.io.externalizable; Import java.io.objectInput; Import java.lang.classNotfoundException; Import java.io.ioException; Import java.io.ObjectOutput; Class readingmaterial2 { String author; String subject; Int yearwritten; Public ReadingMaterial2 () {} ReadingMaterial2 (String Auth, String Sub, Int Year) { Author = auth; Subject = SUB; YearWritten = year; } } The results are as follows: Printing Original Book .. Name: how to serialize Author: r.r Pages: 100 Subject: Serialization Year: 97 Printing new book .. Name: how to serialize Author: r.r Pages: 100 Subject: Serialization Year: 97 Both Original and New Should Be The Same 5. Sequence of evolved / * EvolutionExampleORIGINALCLASS.JAVA * / Import java.io. *; Import java.util. *; Public class evolutionexampleoriginalclass3 { Public static void main (string args []) { Boolean serialize = false; Boolean deserialize = false; IF (args.length == 1) { IF (args [0]. Equals ("- d")) { Deserialize = True; } else if (args [0]. Equals ("- s")) { Serialize = true; } else { USAGE (); System.exit (0); } } else { USAGE (); System.exit (0); } Aclass serialization = new aclass (10, "serializedbyoriginalclass); ACLASS DeSerialization = NULL; IF (serialize) { Try { FileOutputStream fo = new fileoutputstream ("evolve.tmp"); ObjectOutputStream so = New ObjectOutputStream (fo); So.writeObject (Serialization); SO.FLUSH (); } catch (exception e) { System.out.println (e); System.exit (1); } } IF (DeSerialize) { Try { FileInputStream Fi = New FileInputStream ("Evolve.tmp"); ObjectInputStream Si = New ObjectInputStream (Fi); Deserialization = (aclass) Si.ReadObject (); } catch (exception e) { System.out.println (e); System.exit (1); } System.out.println ("Now Printing Deserirated Object's Name:"); SYSTEM.OUT.PRINTLN (); System.out.println ("Name:" DeserialIzeclass.Name); SYSTEM.OUT.PRINTLN (); } } Static void usage () { System.out.println ("USAGE:"); System.out.println ("-s (in order to serialize); System.out.Println ("-d (in Order to DeSerialize); } } Class Aclass IMPLEMENTS Serializable { Private int num; String name; ACLASS (INT N, STRING S) { Num = n; Name = s; } Private void writeobject (ObjectOutputstream S) throws oException { s.defaultwriteObject (); } Private Void ReadObject (ObjectInputStream S) THROWS IEXCEPTION, ClassNotFoundException { S.DEFAULTREADOBJECT (); } Public string toString () { Return ("Name:" Name "/ N" "NUM" NUM "/ N"); } } / * EvolutionExampleEvolvedclass3.java * / Import java.io. *; Import java.util. *; Public class evolutionExampleEvolvedclass3 { Public static void main (string args []) { Boolean serialize = false; Boolean deserialize = false; IF (args.length == 1) { IF (args [0]. Equals ("- d")) { Deserialize = True; } else if (args [0]. Equals ("- s")) { Serialize = true; } else { USAGE (); System.exit (0); } } else { USAGE (); System.exit (0); } Aclass serialization = new aclass (20, "serializedbyoriginalclass); ACLASS DeSerialization = NULL; IF (serialize) { Try { FileOutputStream fo = new fileoutputstream ("evolve.tmp"); ObjectOutputStream so = New ObjectOutputStream (fo); So.writeObject (SerializeClass); SO.FLUSH (); } catch (exception e) { System.out.println (e); System.exit (1); } } IF (DeSerialize) { Try { FileInputStream Fi = New FileInputStream ("Evolve.tmp"); ObjectInputStream Si = New ObjectInputStream (Fi); Deserialization = (aclass) Si.ReadObject (); } catch (exception e) { System.out.println (e); System.exit (1); } System.out.println ("Now Printing Deserirated Object's Name:"); System.out.println (); System.out.println ("Name:" DeserialIzeclass.name "/ n" deserializationclass.num "/ n" deserializeclass.b); System.out.println (); } } Static void usage () { System.out.println ("USAGE:"); System.out.println ("-s (in order to serialize); System.out.Println ("-d (in Order to DeSerialize); } } Class Aclass Implements Serializable { Int Num; Boolean B; String name; ACLASS (INT N, STRING S) { Num = n; Name = s; Boolean b = false; } Private void writeobject (ObjectOutputstream S) throws oException { s.defaultwriteObject (); } Private Void ReadObject (ObjectInputStream S) THROWS IEXCEPTION, ClassNotFoundException { S.DEFAULTREADOBJECT (); } } The results are as follows: Now Printing Deserirated Object's Name: Name: SerializedbyoriginalClass 20 False