Purpose of object serialization
1) Want to persist Java objects in a file
2) Using Java Objects for network transport
Implementation method
If you want an object of a class to be serialized/deserialized, That class must implement the Java.io.Serializable interface or the Java.io.Externalizable interface, which is a markup interface, i.e. there is no method that needs to be implemented, just an object serializable identifier, and the way to serialize and deserialize the system The default method, which in fact internally also implements the serializable, and contains two methods writeexternal () and readexternal () respectively for the object write and read, so you can use a custom way to serialize/deserialize, More flexible than serializable.
There is also an important property serialversionuid when writing a serialization class, which is long and must be static and final, for verifying that the object that is serialized with the deserialized object is the object of the same class. The generation of this value does not recommend using the default values provided by the system dynamically, instead using the IDE's own UID generation feature.
code example
Write a simple class person that implements the serializable interface. Notice that the class has four properties, where company is static,age as transient.
Public classPersonImplementsSerializable {Private Static Final Long Serialversionuid= 7686111088673836789L; Private intID; PrivateString name; Private StaticString Company; Private transientintAge ; Static{ Company= "Apple"; } PublicPerson (intID, String name,intAge ) { Super(); This. ID =ID; This. Name =name; This. Age =Age ; } @Override PublicString toString () {return"Person [id=" + ID + ", name=" + name + ", age=" + Age + "]"; }}
Once a class is serializable, we can pass ObjectOutputStream
/ObjectInputStream将该类的某个对象序列化存储在文件中,并随后从文件中反序列出来还原该对象。
Public classSerializabletest {/**serializing an object to a file*/ Public voidSerialize (Serializable object, String FilePath)throwsIOException {File file=NULL; ObjectOutputStream out=NULL; Try{file=NewFile (FilePath); out=NewObjectOutputStream (Newfileoutputstream (file)); Out.writeobject (object); } Catch(IOException e) {e.printstacktrace (); } finally { if(Out! =NULL) Out.close (); } } /**Deserialize an object from a file*/ PublicObject Deserialize (String FilePath)throwsIOException {File file=NULL; ObjectInputStream in=NULL; Try{file=NewFile (FilePath); Inch=NewObjectInputStream (Newfileinputstream (file)); returnIn.readobject (); } Catch(Exception e) {e.printstacktrace (); } finally { if(In! =NULL) In.close (); } return NULL; } Public Static voidMain (string[] args)throwsIOException {serializabletest test=Newserializabletest (); String FilePath= "Output/person.ser"; Test. Serialize (NewPerson ("Kobe", 37), FilePath);
Person Person=(person) test. Deserialize (FilePath); System.out.println ("Person =" +Person ); }}
Here we generate a person object, pass in three parameters, then store it in the Person.ser file, and then read from the file to deserialize the object. The final output is:
person = person [id=24, Name=kobe, age=0]
ID and name Two values are no problem, why age=0, instead of incoming 37? This is what the transient keyword does, and not all properties will participate in the serialization process, such as attributes identified with the static and transient keywords. Because the static property implies that all objects of the class are owned together and do not belong to a specific object, it should not appear when the object is serialized While the meaning of the transient keyword is intended to be artificially added when certain attributes, such as some sensitive password information, are not expected to be stored in the file. There is, of course, another way to reverse-determine the Serializable property, which is to define a special property of type objectstreamfield[], called Serialpersistentfields, and it must be private, static, and final. It is up to Serialpersistentfields to determine which properties are expected to participate in serialization, including even the default non-serializable static and transient properties (the static property itself has not been tested successfully and is always thrown "unmatched Serializable field (s) declared "exception information, please Daniel do not hesitate to enlighten you." For example:
Public classPersonImplementsSerializable {Private Static Final LongSerialversionuid = -4481514608698081671l; Private transientInteger ID; PrivateString name; Private Static FinalObjectstreamfield[]Serialpersistentfields= {NewObjectstreamfield ("id", Integer.class) };}
In this way, the ID with the transient attribute is serialized, but the name that was originally serialized by default is not serialized, because only the ID is specified as a serializable attribute in Serialpersistentfields.
Serialization Stream Protocol storage format
After serializing the previous person object to a file, open with Binary Viewer binary viewing tool (under Windows platform), let's look at the storage format of the serialized file, as shown ( Note that only the ID and Name properties can be serialized, Company and age do not ).
These hexadecimal numbers represent the meanings followed by the Java object Serialization stream protocol , which in turn describes their meanings.
AC Ed:stream_magic
XX 05:stream_version
73:tc_object
72:tc_classdesc
00 06: The length of the class name, which is the length of the person, is 6
6F 6E: class name, person
6A AA 8D 4F F8 98 4E f5:serialversionuid value of 7686111088673836789
02:classdescflags, this is sc_serializable because the class implements the SERIALIZABLE interface
00 02: Number of attributes, where the number of serializable properties is 2
49:I, which represents int because the ID is of type int
00 02: The length of the attribute name, that is, the length of the ID, 2
69 64: Attribute name, that is, ID
4c:l, which represents the class type, because string is a class type and differs from the base type
00 04: The length of the property name, that is, the length of "name", 4
6E 6D 65: Name of the property
74:tc_string, which represents the string
00 12: The length of the type name, i.e. "ljava/lang/string;" The length of the 18
4C 6A, 2F, 6C, 6E, 2F, 3b:ljava/lang/string, 6E, and more. where L represents a class type (note the end has A; semicolon)
78:tc_endblockdata
70:tc_null
00 00 00 18: Attribute value, which is the value of ID, is 24
74:tc_string, which represents the string
00 04: The length of the property value, that is, the value of name Kobe, is 4
6B 6F 62 65: attribute value, which is the value of name, is Kobe
Customizing the serialization/deserialization process
All classes that implement the Serializable interface actually have several hidden methods that can be overridden to control the entire serialization and deserialization process, such as:
private void writeobject ( ObjectOutputStream out) throws IOException; private void ReadObject (ObjectInputStream in) throws Ioexception,classnotfoundexception;object Writereplace () throws Objectstreamexception;object readresolve () throws objectstreamexception;
where the Writereplace () and Readresolve () methods are hook functions, respectively, before the WriteObject () call and after the ReadObject () call. One of the Readresolve () method in my other blog about Singleton , the purpose is to prevent malicious people through the object serialization technology to destroy the singleton model, to construct a new object, because through the readobject () Methods can construct new objects directly and avoid private construction methods. However, because the Readresolve () method is called after the object is deserialized by ReadObject (), it can be used to replace the read-out stream object.
References:
[1] https://docs.oracle.com/javase/8/docs/platform/serialization/spec/protocol.html#a8299
[2] https://docs.oracle.com/javase/8/docs/platform/serialization/spec/serial-arch.html#a6250
[3] Http://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html
[4] Https://www.javacodegeeks.com/2015/09/built-in-serialization-techniques.html
[5] http://steven2011.iteye.com/blog/1299499
[6] Http://stackoverflow.com/questions/1168348/java-serialization-readobject-vs-readresolve
in order to respect the original results, if necessary reprint please indicate the source of this article: Http://www.cnblogs.com/fernandolee24/p/5682738.html , hereby thank
Parsing of Java object serialization