Object serialization is a way to turn an object into a binary data stream. If an object of a class wants to be serialized, it implements the serializable interface, which is an identity interface (only the interface is defined and no method is defined), indicating that the object has the ability to be serialized.
After implementing the Serializable interface, it indicates that the class has the ability to be transmitted by the data stream, and if you want to enter and output, use two classes: ObjectOutputStream and ObjectInputStream
When serializing, only attributes are serialized
If a property of an object does not want to be serialized, it can be declared using the Transient keyword (this property is transparent and is not considered for serialization).
Serializable interface uses:
ImportJava.io.*; Public classTest { Public Static voidMain (string[] args)throwsException {Try{objectoutputstream Oos=NULL; ObjectInputStream Ois=NULL; File F=NewFile ("E:\\java\\person.txt"); OutputStream OS=NewFileOutputStream (f); InputStream is=NewFileInputStream (f); Oos=Newobjectoutputstream (OS); Ois=NewObjectInputStream (IS); Person P1=NewPerson (23, "Baby", 180.00); Oos.writeobject (p1); Oos.close (); Person P2=(person) ois.readobject (); Ois.close (); System.out.println (p2); }Catch(IOException e) {e.printstacktrace (); } } }classPersonImplementsSerializable {intAge = 8; String name; transient Doubleheight = 170;//The variable declared by transient is not considered at serialization, so it is the default value 0 when deserializingPerson (intAge,string name,Doubleheight) { This. Age =Age ; This. Name =name; This. Height =height; } PublicString toString () {return"Name:" + This. Name + "Age:" + This. Age + "Height:" + This. Height; }}
Serialization of Java Learning Note objects