Overview: When a class implements the serializable interface (this interface is only a tag interface and does not contain any method definition), it indicates that the class can be serialized. the purpose of serialization is to convert an object that implements the serializable interface into a byte sequence.
Save the byte sequence (for example, saving it in a file), and you can restore the sequence to the original object at any time. You can even put the byte sequence on another computer or transmit it to another computer over the network for restoration.
If the computing platform has a corresponding class, it can be restored to the original object.
Implementation: to serialize an object, you must first create some outputstream objects, encapsulate them in an objectoutputstream object, and then call the writeobject () method to serialize an object. deserialization is similar.
Import java. Io .*;
Public class person implements serializable {
Private string username;
Private string password;
Public Person (string username, string password ){
This. Username = username;
This. Password = password;
}
Public String tostring (){
Return "username:" + username + "Password:" + password;
}
Public static void main (string [] ARGs) throws filenotfoundexception, ioexception, classnotfoundexception {
// Serialize an object (stored in a file)
Objectoutputstream OOS = new objectoutputstream (New fileoutputstream ("person. Out "));
Oos. writeobject ("Save a object: \ n ");
Oos. writeobject (new person ("Bruce", "123456 "));
Oos. Close ();
// Deserialization, restore the object (stored in a file)
Objectinputstream OIS = new objectinputstream (New fileinputstream ("person. Out "));
String S = (string) Ois. readobject ();
Person P = (person) Ois. readobject ();
System. Out. println (S + p );
// Serialize an object (stored in a byte array)
Bytearrayoutputstream baos = new bytearrayoutputstream ();
Objectoutputstream oos2 = new objectoutputstream (baos );
Oos2.writeobject ("save another object: \ n ");
Oos2.writeobject (new persons ("Phil", "654321 "));
Oos2.close ();
// Deserialization, restore the object (stored in byte array)
Objectinputstream ois2 = new objectinputstream (New bytearrayinputstream (baos. tobytearray ()));
S = (string) ois2.readobject ();
P = (person) ois2.readobject ();
System. Out. println (S + p );
}
}
// Enter the following information:
Save a object:
Username: Bruce password: 123456
Save another object:
Username: Phil password: 654321
Transient Keyword:
Automatic serialization makes all fields of the Object Persistent. Sometimes some fields need not be automated (such as passwords, because serialization will expose the password information ), in this case, you can use the transient keyword (which can only be used with the serializable object
Is not serialized. Change the field of the person class to the following definition, and then run the above program:
Private string username;
Private transient string password;
// Enter the following information:
Save a object:
Username: Bruce password: NULL
Save another object:
Username: Phil password: NULL
Control the serialization field. Even a field modified by transient can be serialized. For manual serialization, you need to add two private methods (writeobject () and readobject () to control the serial flower fields in this private method.
Import java. Io .*;
Public class person implements serializable {
Private string username;
Private transient string password;
Public Person (string username, string password ){
This. Username = username;
This. Password = password;
}
Public String tostring (){
Return "username:" + username + "Password:" + password;
}
Private void writeobject (objectoutputstream out) throws ioexception {
Out. defaultwriteobject (); // serialize all non-transient fields, which must be the first operation of this method
Out. writeobject (password); // serialize the transient field
}
Private void readobject (objectinputstream in) throws ioexception, classnotfoundexception {
In. defaultreadobject (); // deserializes all non-transient fields, which must be the first operation of this method.
Password = (string) in. readobject (); // deserialize the transient field
}
Public static void main (string [] ARGs) throws filenotfoundexception, ioexception, classnotfoundexception {
// Serialize an object (stored in a file)
Objectoutputstream OOS = new objectoutputstream (New fileoutputstream ("person. Out "));
Oos. writeobject ("Save a object: \ n ");
Oos. writeobject (new person ("Bruce", "123456 "));
Oos. Close ();
// Deserialization, restore the object (stored in a file)
Objectinputstream OIS = new objectinputstream (New fileinputstream ("person. Out "));
String S = (string) Ois. readobject ();
Person P = (person) Ois. readobject ();
System. Out. println (S + p );
}
}
// Enter the following information:
Save a object:
Username: David password: 13579
You can also use the externalizable interface to control serialized fields to replace serializable. Define a default constructor. Otherwise, an exception (Java. Io. invalidclassexception: person; no
Valid constructor); you also need to define two methods (writeexternal () and readexternal () to control the fields to be serialized.
Import java. Io .*;
Public class person implements externalizable {
Private string username;
Private string password;
Public Person (){
System. Out. println ("default constructor invoked! ");
}
Public Person (string username, string password ){
This. Username = username;
This. Password = password;
}
Public String tostring (){
Return "username:" + username + "Password:" + password;
}
Public void writeexternal (objectoutput out) throws ioexception {
// Serialize a field
Out. writeobject (username );
Out. writeobject (password );
}
Public void readexternal (objectinput in) throws ioexception, classnotfoundexception {
// Deserialization Field
Username = (string) in. readobject ();
Password = (string) in. readobject ();
}
Public static void main (string [] ARGs) throws filenotfoundexception, ioexception, classnotfoundexception {
// Serialize an object (stored in a file)
Objectoutputstream OOS = new objectoutputstream (New fileoutputstream ("person. Out "));
Oos. writeobject ("Save a object: \ n ");
Oos. writeobject (new person ("Leo", "1984 "));
Oos. Close ();
// Deserialization, restore the object (stored in a file)
Objectinputstream OIS = new objectinputstream (New fileinputstream ("person. Out "));
String S = (string) Ois. readobject ();
Person P = (person) Ois. readobject ();
System. Out. println (S + p );
}
}
// Enter the following information:
Default constructor invoked!
Save a object:
Username: Leo password: 1984
About serialversionuid In the serializable interface class:
Serialversionuid is of the long type. There are two generation methods in Eclipse:
The default value is 1l:
private static final long serialVersionUID = 1L;
The other is to generate a 64-bit hash field based on the class name, Interface Name, member method, and attribute:
private static final long serialVersionUID = 3969438177161438988L;
Serialversionuid is mainly used to solve the compatibility problem of object deserialization.
If serialversionuid is not provided, after the object is serialized and saved to the hard disk, the filed of the class is added or reduced. In this way, exception occurs during deserialization, resulting in incompatibility issues.
However, when the serialversionuid is the same, it deserializes different fields with the default value of type. This avoids incompatibility issues.
The above method can only be restored to a Java object. If you want to restore to another object (such as a C ++ object), you need to convert the Java object to the XML format, in this way, it can be used by various platforms and languages. You can use the javax. Xam. * Class Library released along with JDK, or use the open-source XOM class library (you can download and obtain documents from www. XOM. Nu ).
Since Java is used, serialization is everywhere. As to why serialization and serialization are used to solve problems, as a common coders, it is generally not very in-depth research, recently, Mina and the company are looking at some of the NIO Framework's source code, which involves hession and Java serialization. As for why hession serialization was born and is widely used in Apache projects, and what are the defects in Java serialization? To answer the questions raised above and learn more about Java serialization mechanism, a small header is provided here, starting with serializable, the serialization interface of Java.
The comments of the serializable interface in the JDK package mainly explain the following:
1. The class enables serialization by implementing the serializable interface. Otherwise, the status of the class cannot be serialized, and it cannot be used for deserialization.
2. If the inherited parent class does not implement the serializable interface, but the subclass can be serialized, there are three considerations:
A ). Serializable interface for subclass implementation
B ). The subclass must have an accessible non-parametric constructor to save and restore the state of the public, protected, or package field of the parent class, otherwise, a runtimeexception exception is thrown during serialization or deserialization.
C ). During deserialization, the status or value of the private (inaccessible) object variable in the parent class cannot be initialized theoretically.
3. When serializing attributes in a serializable class, if an object variable that is not serializable is encountered, A notserializableexception exception will be thrown for the class that is not serializable.
4. for non-array classes that can be serialized, it is strongly recommended that the declared static, long, and final serialversionuid fields be displayed to identify the version number of the current serialization class, otherwise, the invalidclassexception exception may occur during serialization and deserialization across operating systems and compilers.
5. for static and transient object variables in a serializable class, the status or value cannot be saved during serialization, the value obtained by static object variables in deserialization is the value of the static variable corresponding to the corresponding class in the current JVM, and transient (transient) keyword is generally used to identify state variables that do not need to be passed during serialization.
Simple test code:
01 import Java. io. fileinputstream; 02 import Java. io. filenotfoundexception; 03 import Java. io. fileoutputstream; 04 import Java. io. ioexception; 05 import Java. io. objectinputstream; 06 import Java. io. objectoutputstream; 07 import Java. io. serializable; 08
09/** 10 * serialization TEST 11*12 * @ author Sume 13*14 */15 public
Class serializableimpl implements serializable {16
17 Private Static final long serialversionuid =-6433786313435044319l; 18
19 static string staticval = "static1"; 20 transient string transientval = "transient1"; 21 string val = "val1"; 22
23/** 24 * main 25 */26 public static void main (string [] ARGs) throws filenotfoundexception, ioexception, classnotfoundexception {27 // serializableimpl sila1 = new serializableimpl (); 29 objectoutputstream = new objectoutputstream (New
Fileoutputstream ("serializable.txt"); 30 objectoutputstream. writeobject (sila1); 31 objectoutputstream. Close (); 32
33 // deserialization 34 serializableimpl. staticval = "static2"; 35 objectinputstream = new objectinputstream (New fileinputstream ("serializable.txt"); 36 serializableimpl sila2 = (serializableimpl) objectinputstream. readobject (); 37 objectinputstream. close (); 38
39 // compare the values of each attribute to 40 system. out. println (sila2.staticval); 41 system. out. println (sila2.transientval); 42 system. out. println (sila2.val); 43} 44} output result: 1 static2 2 null 3 val1 from the output result:
1. The value of the static variable staticval in the Post-deserialization class is the value of the static variable corresponding to the current JVM, Which is static2, rather than the value of static1 during serialization.
2. The status of the variable identified by the transient keyword is not saved in serialization. Therefore, after deserialization
The value of transientval is null.
3. The third is the transmission of Common Object States during serialization and deserialization.
Briefly confirms the content mentioned above